only-item-middle = board-start + (end + initial) / 2
Now our middle index is 7. We compare the value in this index to the value to search.
The value in index 7 is not connected, and in addition, the value to look for is less than the value in index 7 so we need to look in the sub-array to the left of this index.
Continue to find the middle-item again. This time it's worth 5.
Compare the value in index 5 with the value to find and find that it connects.
Therefore we conclude that the value to be searched for is stored at index position 5.
Binary Search bisects the number of elements needed and thus reduces the number of comparisons that need to be performed, so this search algorithm is done quite quickly.
Below is the sample code for binary search algorithm:
Binary Search algorithm (Binary Search)
A ← an array has been sorted
n ← array size
x ← value to search in the array
assign lowerBound = 1
assign upperBound = n
trong khi x không tìm thấy
if upperBoundEXIT: x does not exist.
assign midPoint = lowerBound + (upperBound - lowerBound) / 2
if A [midPoint]assign lowerBound = midPoint + 1
if A [midPoint]> x
assign upperBound = midPoint - 1
if A [midPoint] = x
EXIT: x is found at midPoint
while end
End the algorithm
According to Tutorialspoint
Previous article: Linear search algorithm (Linear Search)
Next lesson: Interpolation Search algorithm (Interpolation Search)