TheAlgorithms / MATLAB-Octave

This repository contains algorithms written in MATLAB/Octave. Developing algorithms in the MATLAB environment empowers you to explore and refine ideas, and enables you test and verify your algorithm.
MIT License
364 stars 173 forks source link

Fix binary search #77

Closed MaximSmolskiy closed 3 years ago

MaximSmolskiy commented 3 years ago

Current binary search implementation has bug. For example,

>> binary_search(1:100, 30)
target is not found in aray
>> binary_search(1:100, 70)
target is not found in aray

The bug is in maximum iteration needed to find the target. There should be binary logarithm log2 instead of natural log. In case of natural logarithm log algorithm lacks iterations in some cases (e.g. in above). But in some cases it works properly. For example,

>> binary_search(1:100, 50)

ans =

    50
cozek commented 3 years ago

Thanks!