πΎ Archived View for hanicef.me βΊ document βΊ binary-search captured on 2022-07-16 at 13:30:30. Gemini links have been rewritten to link to archived content
-=-=-=-=-=-=-
(C) Gustaf AlhΓ€ll, released under CC BY 4.0
Original document can be found at hanicef.me
License can be found at creativecommons.org
The binary search algorithm is a simple algorithm for finding a value in an ordered list quickly. It's complexity is O(log(n)), and is easy to implement.
The algorithm works by eliminating half of all possible values in every step, until there's only one value left. For example, consider the following list:
βββββ¬ββββ¬ββββ¬ββββ¬ββββ¬βββββ¬βββββ β 2 β 3 β 5 β 8 β 9 β 11 β 12 β βββββ΄ββββ΄ββββ΄ββββ΄ββββ΄βββββ΄βββββ
Let's say we want to locate 5. We start by looking at the center of the list (on 8) and comparing it with the value we want to find. The process works like so:
In this case, 5 is less than 8, so that means all values above it is also eliminated in the process. Thus, the values 8, 9, 11 and 12 are all eliminated. This only leaves us with 2, 3 and 5:
Remaining Eliminated βββββ¬ββββ¬ββββ βββββ¬ββββ¬βββββ¬βββββ β 2 β 3 β 5 β β 8 β 9 β 11 β 12 β βββββ΄ββββ΄ββββ βββββ΄ββββ΄βββββ΄βββββ
Now, we repeat the process with only the remaining values. In this case, the center is 3, and so we compare 3 with 5. 5 is greater than 3, so we eliminate all values below it:
Eliminated Result Eliminated βββββ¬ββββ βββββ βββββ¬ββββ¬βββββ¬βββββ β 2 β 3 β β 5 β β 8 β 9 β 11 β 12 β βββββ΄ββββ βββββ βββββ΄ββββ΄βββββ΄βββββ
This leaves us with only one value left, which is 5. And so, we have found the value 5 in an ordered list in just 2 iterations.
Assuming we want to find v in the list A, implementing binary search involving the following steps:
Then repeat the following steps until either v is found or l > r:
If l > r, the value v doesn't exist in A, and the algorithm can terminate.
The algorithm can be implemented like this in C:
int binary_search(int *A, int n, int v) { int l = 0, r = n - 1, i; while (l < r) { i = (l + r) / 2; if (v == A[i]) { return i; } else if (v < A[i]) { r = i - 1; } else if (v > A[i]) { l = i + 1; } } return -1; }
This function returns the index where v is located in A, or -1 if that value cannot be found.