Binary search is one of the most popular searching algorithms (Binary Search Algorithm). It works only in a sorted array. It utilizes the concept of decrease and conquer. At each iteration, it halves the size of the array while searching for an element in a list of items.
While Matlab provides the 'find' or similar functions to search for an element in an array. This problem works the other way around. You have to implement the binary search algorithm here. Instead of finding the index of an element, you've to find how many jumps/iterations do you need using binary search to reach the item you are looking for.
For example,
given array, a= [2, 4, 5, 7, 8, 9, 19] and search item value= 8.
The item is located at index 5. But thats not what you are looking for.
Implementing Binary search --
- step - 1: mid_elem = 7. doesn't match and lower. so shift the search to upper half. new array is [8, 9, 19].
- step - 2: mid_elem = 9. doesn't match and higher. so, shift the search to lower half. new array is [8].
- step - 3: mid_elem=8. match.
So, no of steps =3.
If the value is not found, return -1.
Solution Stats
Problem Comments
1 Comment
Solution Comments
Show comments
Loading...
Problem Recent Solvers10
Suggested Problems
-
17385 Solvers
-
13215 Solvers
-
306 Solvers
-
How many monitors are connected ?
157 Solvers
-
1761 Solvers
More from this Author174
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
Test suite updated with a random input and solutions rescored.