Loading subject…
Searching for 8 takes three comparisons and returns index 2.
| i | arr[i] | arr[i] == 8? | Action |
|---|---|---|---|
| 0 | 5 | No | Move to the next element |
| 1 | 3 | No | Move to the next element |
| 2 | 8 | Yes | Return 2 |
| Pass | left | right | mid | arr[mid] | Comparison | Action |
|---|---|---|---|---|---|---|
| 1 | 0 | 12 | 6 | 45 | 139 > 45 | left = 7 |
| 2 | 7 | 12 | 9 | 139 | 139 = 139 | Return 9 |
Searching for 100 is the worst case, and the loop ends when left passes right.
| Pass | left | right | mid | arr[mid] | Comparison | Action |
|---|---|---|---|---|---|---|
| 1 | 0 | 12 | 6 | 45 | 100 > 45 | left = 7 |
| 2 | 7 | 12 | 9 | 139 | 100 < 139 | right = 8 |
| 3 | 7 | 8 | 7 | 84 | 100 > 84 | left = 8 |
| 4 | 8 | 8 | 8 | 129 | 100 < 129 | right = 7 |
| 5 | 8 | 7 | - | - | left > right | Return -1 |
| Criterion | Linear search | Binary search |
|---|---|---|
| Data must be sorted | No | Yes |
| Best case | O(1) | O(1) |
| Average case | O(n) | O(log n) |
| Worst case | O(n) | O(log n) |
| Space complexity | O(1) | O(1) |
| Comparisons on 1,000,000 items (worst case) | 1,000,000 | 20 |
| Works on linked data with no index | Yes | No |
def linear_search(arr, target): # Check every element in turn for i in range(len(arr)): if arr[i] == target: # match found return i return -1 # target is not in the list
numbers = [5, 3, 8, 4, 2]print(linear_search(numbers, 8)) # Output: 2print(linear_search(numbers, 7)) # Output: -1public static int linearSearch(int[] arr, int target) { // Check every element in turn for (int i = 0; i < arr.length; i++) { if (arr[i] == target) { // match found return i; } } return -1; // target is not in the array}
int[] numbers = {5, 3, 8, 4, 2};System.out.println(linearSearch(numbers, 8)); // Output: 2System.out.println(linearSearch(numbers, 7)); // Output: -1def binary_search(arr, target): left = 0 right = len(arr) - 1
while left <= right: mid = (left + right) // 2 # midpoint of the remaining range if arr[mid] == target: return mid # target found elif arr[mid] < target: left = mid + 1 # discard the lower half else: right = mid - 1 # discard the upper half
return -1 # target is not in the list
numbers = [2, 4, 6, 8, 10, 12, 14]print(binary_search(numbers, 10)) # Output: 4print(binary_search(numbers, 5)) # Output: -1public static int binarySearch(int[] arr, int target) { int left = 0; int right = arr.length - 1;
while (left <= right) { int mid = (left + right) / 2; // midpoint of the remaining range if (arr[mid] == target) { return mid; // target found } else if (arr[mid] < target) { left = mid + 1; // discard the lower half } else { right = mid - 1; // discard the upper half } } return -1; // target is not in the array}
int[] numbers = {2, 4, 6, 8, 10, 12, 14};System.out.println(binarySearch(numbers, 10)); // Output: 4System.out.println(binarySearch(numbers, 5)); // Output: -1