Binary search is an efficient O(log n)
way to search for a specific item in a list of sorted data,
e.g. a list of integers [1, 2, 5, 8, 10, 18, 32, 60]
.
Given: sorted list, target
value, start
index, end
index.
Initial case: start = 0, end = list.size
mid = (start + end) / 2
midpoint = list[mid]
target = midpoint
, then the value has been found. Return mid
, which is the index of the target value.target < midpoint
, make a recursive call to search the lower half of the list.
binarySearch(list, target, start, mid)
target > midpoint
, make a recursive call to search the upper half of the list.
binarySearch(list, target, mid + 1, end)