Loading your workspace…
Loading your workspace…
Search for a key in a sorted array of integers using binary search and report its position, or that it is absent.
#include <stdio.h>
#define MAX_SIZE 100
int binary_search(const int arr[], int n, int key) {
int low = 0;
int high = n - 1;
int mid;
while (low <= high) {
mid = low + (high - low) / 2;
if (arr[mid] == key) {
return mid;
}
if (key < arr[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
int main(void) {
int arr[MAX_SIZE];
int n, i, key, pos;
printf("Enter number of elements (1-%d):\n", MAX_SIZE);
if (scanf("%d", &n) != 1 || n < 1 || n > MAX_SIZE) {
printf("Error: invalid size\n");
return 1;
}
printf("Enter %d elements in ascending order:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter key to search:\n");
scanf("%d", &key);
pos = binary_search(arr, n, key);
if (pos >= 0) {
printf("Element %d found at position %d (1-based)\n", key, pos + 1);
} else {
printf("Element %d not found\n", key);
}
return 0;
}
Input
7
2 5 8 12 16 23 38
23Output
Enter number of elements (1-100):
Enter 7 elements in ascending order:
Enter key to search:
Element 23 found at position 6 (1-based)Input
7
2 5 8 12 16 23 38
1Output
Enter number of elements (1-100):
Enter 7 elements in ascending order:
Enter key to search:
Element 1 not foundBinary search works only on sorted data. Each comparison with the middle element discards the half of the range that cannot contain the key, so a list of n items needs at most about log2(n) + 1 comparisons.
mid is computed as low + (high - low) / 2 rather than (low + high) / 2. The two are equal in value, but the first form cannot overflow when low and high are both large.
Edit the program and press Run. It is free and needs no sign-in.
Copy a sample and paste it into the STDIN box in the editor before you press Run.
7 2 5 8 12 16 23 38 23
Expected output
Enter number of elements (1-100): Enter 7 elements in ascending order: Enter key to search: Element 23 found at position 6 (1-based)
7 2 5 8 12 16 23 38 1
Expected output
Enter number of elements (1-100): Enter 7 elements in ascending order: Enter key to search: Element 1 not found
It must be sorted in ascending order; on unsorted data the halving step can discard the key.
About log2(n) + 1, since the range is halved on every step.
-1 is not a valid index, so it safely signals not found.
It gives the same value as (low + high) / 2 but avoids overflow of the sum when both indices are large.
An array parameter decays to a pointer, so the function cannot find the length of the array by itself.
Back to all VTU BPOPS103 lab programs.