Run ❯
Get your
own
website
❯
Run Code
Ctrl+Alt+R
Change Orientation
Ctrl+Alt+O
Change Theme
Ctrl+Alt+D
Go to Spaces
Ctrl+Alt+P
#include
// Returns the index of the value, or -1 if it is not found int binarySearch(int arr[], int length, int value) { int low = 0; int high = length - 1; while (low <= high) { int middle = (low + high) / 2; printf("Checking index %d (value %d)\n", middle, arr[middle]); if (arr[middle] == value) { return middle; // Found it } else if (arr[middle] < value) { low = middle + 1; // Search the right half } else { high = middle - 1; // Search the left half } } return -1; // Not found } int main() { int numbers[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91}; int length = sizeof(numbers) / sizeof(numbers[0]); int index = binarySearch(numbers, length, 23); if (index != -1) { printf("Found 23 at index %d\n", index); } else { printf("23 was not found\n"); } return 0; }
Checking index 4 (value 16)
Checking index 7 (value 56)
Checking index 5 (value 23)
Found 23 at index 5