Binary Search
See it animated in Zerethon Tools ↗Find a value in a sorted list by halving the search range at every step — O(log n).
This is an older version. The current version is 1.5.0.
Implementations
Java can be viewed here but not run in Zerethon IDE yet.
Files
// Zerethon Official Sample: binary-search 1.0.0 (view only — the IDE cannot run Java yet).
public class BinarySearch {
// a must be sorted ascending. Returns the index of target, or -1.
static int binarySearch(int[] a, int target) {
int lo = 0, hi = a.length - 1;
while (lo <= hi) {
int mid = (lo + hi) >>> 1;
if (a[mid] == target) return mid;
if (a[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
public static void main(String[] args) {
int[] numbers = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
for (int target : new int[] {23, 2, 91, 7}) {
int index = binarySearch(numbers, target);
System.out.println("search " + target + ": " + (index == -1 ? "not found" : "found at index " + index));
}
}
}
Source: Zerethon Official Sample. Algorithm as shown in the Zerethon Tools Binary Search Visualizer.