Problem 56040. A Binary Search
- Calculate the index of the midpoint of the array X by taking the average of the largest and smallest indices and rounding to the nearest integer.
- If the value located at the midpoint matches your target, set found to true.
- If the target is less than the value located at the midpoint of X, narrow your search to the lower half of X by setting the largest index in the array to the midpoint - 1.
- If the target is greater than the value located at the midpoint of X, narrow your search to the upper half of X by setting the smallest index in the array to the midpoint + 1.
- Repeat the steps above until found is true.
Solution Stats
Problem Comments
-
6 Comments
Very interesting problem, thanks!
I would like to know if anyone else is getting a discrepancy in tests 5 and 6. My number of iterations is one less than the expected in those two test sets. I had to start my iteration counter with 2 to get the expected results.
@Jose, it's not a discrepancy, that is how one is suppose to calculate the number of iterations for this problem, as you can see from the example in the problem description.
Solution Comments
Show commentsProblem Recent Solvers73
Suggested Problems
-
Determine whether a vector is monotonically increasing
21344 Solvers
-
Numbers with prime factors 2, 3 and 5.
578 Solvers
-
Solve the set of simultaneous linear equations
435 Solvers
-
Given a square and a circle, please decide whether the square covers more area.
1215 Solvers
-
237 Solvers
More from this Author10
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!