Problem 55285. Number of leaps in binary search

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 --
  1. step - 1: mid_elem = 7. doesn't match and lower. so shift the search to upper half. new array is [8, 9, 19].
  2. step - 2: mid_elem = 9. doesn't match and higher. so, shift the search to lower half. new array is [8].
  3. step - 3: mid_elem=8. match.
So, no of steps =3.
If the value is not found, return -1.

Solution Stats

56.25% Correct | 43.75% Incorrect
Last Solution submitted on May 03, 2024

Problem Comments

Solution Comments

Show comments

Problem Recent Solvers7

Suggested Problems

More from this Author165

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!