Searching finds an element (or its position) in a collection. Linear search checks items one by one and works on any array in O(n). Binary search repeatedly halves a sorted array and finds an item in O(log n). This section covers the search contract, linear search, iterative and recursive binary search, and how to choose between them.
Sorted data unlocks speed.
Binary search is only valid on sorted data. Sorting costs O(n log n), so it pays off when you search many times.
Path
Learning Path
Work through the stages in order, or jump to a topic from the index below (6 tutorials).
A quick taste of searching. Compile with gcc file.c -std=c11 -Wall -o out.
Example 1 — Search and return an index
The usual contract: the index, or -1 when absent.
C
#include <stdio.h>
static int find(const int a[], int n, int key) {
for (int i = 0; i < n; i++)
if (a[i] == key) return i;
return -1;
}
int main(void) {
int a[] = {10, 20, 30, 40, 50};
printf("index of 40: %d\n", find(a, 5, 40));
printf("index of 35: %d\n", find(a, 5, 35));
return 0;
}
Output
index of 40: 3
index of 35: -1
How It Works
The function returns the position of the first match.
It returns -1 because -1 is never a valid index.
Callers must check for -1 before using the result.
Index
C Searching Algorithms Topics
Every guide in this section with a one-line summary (6 tutorials).