Binary Search in C
Level 5311 keystrokes
Implements binary search on a sorted array: it compares the target with the middle element and halves the search range each time. Searching for 7 in {1, 3, 5, 7, 9} prints its index, 3.
C code
// Returns the index of target in the sorted array, or -1 if it is absent1int binarySearch(int arr[], int n, int target) { // The search range starts as the whole array2 int left = 0, right = n - 1; // Repeats while the range still contains at least one element3 while (left <= right) { // Index of the middle of the current range (first pass: 2)4 int mid = (left + right) / 2; // Found: returns the index right away5 if (arr[mid] == target) return mid; // Middle value too small: the target can only be in the right half6 if (arr[mid] < target) left = mid + 1; // Otherwise the target can only be in the left half7 else right = mid - 1;8 } // The range became empty, so target is not in the array9 return -1;10}// Binary search only works on sorted data11int arr[] = {1, 3, 5, 7, 9};// 7 is at index 3, so this prints 312printf("%d", binarySearch(arr, 5, 7));Output
3
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this C code and how often they appear.
,× 10=× 9;× 8(× 7)× 7[× 4]× 4-× 3{× 3}× 3