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 absent
1int binarySearch(int arr[], int n, int target) {
// The search range starts as the whole array
2 int left = 0, right = n - 1;
// Repeats while the range still contains at least one element
3 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 away
5 if (arr[mid] == target) return mid;
// Middle value too small: the target can only be in the right half
6 if (arr[mid] < target) left = mid + 1;
// Otherwise the target can only be in the left half
7 else right = mid - 1;
8 }
// The range became empty, so target is not in the array
9 return -1;
10}
// Binary search only works on sorted data
11int arr[] = {1, 3, 5, 7, 9};
// 7 is at index 3, so this prints 3
12printf("%d", binarySearch(arr, 5, 7));

Output

3
Practice typing this code

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

More C examples at level 5

← C typing practice