Skip to the task
Layout
Back to classic view

You are looking at lesson 6. Your place is still lesson 5, task 1: Functions.

CHECKTask 14 of 28 · step 6: Linear and binary searchAn unsorted array
An unsorted array in practice/06/

What would binary_search return if the array held 5 3 9 1 7 and you looked for 3?

Numbered notes in the code explain the important lines.

Details & hint

Stuck? -1. The middle is 9 (index 2); 9 > 3, so right = 1. Then the middle is 5 (index 0); 5 > 3, right = -1, and the search ends, though 3 is at index 1. Binary search works only on a sorted array.

practice 06 search.c Code Diff +66
A · NEW FILE Create this file. Every line is new: see the green bar.
#include <assert.h>
#include <stdio.h>
#define N 1000
/* How many elements the last search checked. For measuring only. */
int checks = 0;
Note 1: A global variable: every function sees it. Only for measuring.
/* Linear search.
Before: 0 <= n.
After: the index of x, or -1 if x is not there. */
int linear_search(const int a[], int n, int x) {
assert(n >= 0);
for (int i = 0; i < n; i++) {
checks++;
if (a[i] == x) {
return i;
}
}
return -1;
}
/* Binary search.
Before: 0 <= n, a is sorted in ascending order.
After: the index of x, or -1 if x is not there. */
int binary_search(const int a[], int n, int x) {
assert(n >= 0);
int left = 0;
int right = n - 1;
while (left <= right) {
int middle = left + (right - left) / 2;
Note 2: Like (left + right) / 2, but the sum can't overflow an int.
checks++;
if (a[middle] == x) {
return middle;
}
if (a[middle] < x) {
left = middle + 1;
Note 3: The middle is already checked: it isn't taken into the new part.
} else {
right = middle - 1;
}
}
return -1;
}
int main(void) {
int numbers[N];
for (int i = 0; i < N; i++) {
numbers[i] = 2 * i;
}
int targets[] = {0, 998, 1998, 7};
Note 4: The compiler works out the size: 4.
int count = (int)(sizeof targets / sizeof targets[0]);
printf("Target Linear Binary\n");
for (int k = 0; k < count; k++) {
checks = 0;
int pos = linear_search(numbers, N, targets[k]);
int linear_checks = checks;
checks = 0;
int pos2 = binary_search(numbers, N, targets[k]);
assert(pos2 == pos);
Note 5: The search is called before the assert: in Release mode it still runs.
printf("%6d %6d %6d\n", targets[k], linear_checks, checks);
}
return 0;
}