Sorting and searching in K&R C
last modified December 5, 2026 K&R C 1978
Sorting and searching run through the whole book. The chapter on control flow sorts with Shell's method, the chapter on functions sorts with quicksort to show recursion, and the chapter on control flow also searches a sorted array by halving it. This article writes these algorithms, counts how much work they do, and then uses the sort and search functions of the library.
Insertion sort
Insertion sort is the simplest of the sorts. It keeps the start of the array sorted and takes the following elements one by one, moving each to its place in the sorted part.
#include <stdio.h>
/* sort v[0]...v[n-1] into increasing order */
int inssort(v, n)
int v[];
int n;
{
int i, j, x;
for (i = 1; i < n; i++) {
x = v[i];
for (j = i - 1; j >= 0 && v[j] > x; j--)
v[j + 1] = v[j];
v[j + 1] = x;
}
return 0;
}
int main()
{
static int v[] = { 31, 4, 15, 9, 26, 5, 3, 58, 97, 23 };
int i;
inssort(v, 10);
for (i = 0; i < 10; i++)
printf("%d ", v[i]);
printf("\n");
return 0;
}
For each i, the element v[i] is saved in
x, and the larger elements before it move one place to the
right until the place for x is found. The inner loop stops
at the start of the array or at an element that is not larger, so equal
elements keep their order. The array is static, so it can
have an initializer.
$ gcc -std=c89 -pedantic -Wall -Wextra -o insertion insertion.c $ ./insertion 3 4 5 9 15 23 26 31 58 97
Shell sort
Insertion sort moves an element one place at a time, so an element far from its place costs many steps. In 1959, D. L. Shell published a method that first compares elements far apart, which moves them a long way in one exchange, and then works with smaller and smaller distances. The book uses it to show nested loops.
#include <stdio.h>
#define N 10
int show(v, n)
int v[];
int n;
{
int i;
for (i = 0; i < n; i++)
printf("%3d", v[i]);
printf("\n");
return 0;
}
/* Shell sort: compare elements gap apart, then halve the gap */
int shellsort(v, n)
int v[];
int n;
{
int gap, i, j, temp;
for (gap = n / 2; gap > 0; gap /= 2) {
for (i = gap; i < n; i++)
for (j = i - gap; j >= 0 && v[j] > v[j + gap]; j -= gap) {
temp = v[j];
v[j] = v[j + gap];
v[j + gap] = temp;
}
printf("gap %d:", gap);
show(v, n);
}
return 0;
}
int main()
{
static int v[N] = { 31, 4, 15, 9, 26, 5, 3, 58, 97, 23 };
printf("start:");
show(v, N);
shellsort(v, N);
return 0;
}
The outer loop sets the distance gap, starting at half the
size of the array and halving it each time. The two inner loops do an
insertion sort on the elements that are gap apart, exchanging
neighbours of that distance while they are out of order. The last pass,
with gap 1, is an ordinary insertion sort, so the array is
sorted at the end. By then, the earlier passes have left little work
for it. The program prints the array after each pass.
$ gcc -std=c89 -pedantic -Wall -Wextra -o shell shell.c $ ./shell start: 31 4 15 9 26 5 3 58 97 23 gap 5: 5 3 15 9 23 31 4 58 97 26 gap 2: 4 3 5 9 15 26 23 31 97 58 gap 1: 3 4 5 9 15 23 26 31 58 97
Counting comparisons
How much faster is Shell sort? A sort spends most of its time comparing elements, so counting the comparisons measures its work on any machine.
#include <stdio.h>
#include <stdlib.h>
#define N 2000
long ncomp; /* comparisons made by the last sort */
int inssort(v, n)
int v[];
int n;
{
int i, j, x;
for (i = 1; i < n; i++) {
x = v[i];
for (j = i - 1; j >= 0 && (ncomp++, v[j] > x); j--)
v[j + 1] = v[j];
v[j + 1] = x;
}
return 0;
}
int shellsort(v, n)
int v[];
int n;
{
int gap, i, j, temp;
for (gap = n / 2; gap > 0; gap /= 2)
for (i = gap; i < n; i++)
for (j = i - gap; j >= 0 && (ncomp++, v[j] > v[j + gap]);
j -= gap) {
temp = v[j];
v[j] = v[j + gap];
v[j + gap] = temp;
}
return 0;
}
int a[N], b[N];
int main()
{
int i, n;
srand(1);
for (i = 0; i < N; i++)
a[i] = b[i] = rand() % 10000;
for (n = 250; n <= N; n *= 2) {
ncomp = 0;
inssort(a, n);
printf("%5d numbers: insertion %8ld", n, ncomp);
ncomp = 0;
shellsort(b, n);
printf(", Shell %6ld\n", ncomp);
for (i = 0; i < n; i++)
a[i] = b[i] = rand() % 10000;
}
return 0;
}
Both sorts increment the external counter ncomp before each
comparison of two elements. The comma operator in the loop condition
evaluates ncomp++ first and gives the value of the
comparison. The arrays a and b get the same
random numbers, and the program sorts the first 250, 500, 1000, and 2000
of them.
$ gcc -std=c89 -pedantic -Wall -Wextra -o compare compare.c $ ./compare 250 numbers: insertion 14195, Shell 2553 500 numbers: insertion 62771, Shell 6437 1000 numbers: insertion 251306, Shell 15115 2000 numbers: insertion 1001313, Shell 35332
Doubling the number of elements multiplies the work of insertion sort by
four: a random array needs about n²/4 comparisons. Shell sort does
little more than twice the work for twice the elements, and at 2000
numbers it is nearly thirty times faster. rand gives other
numbers on other machines, so the counts differ a little from machine
to machine.
Quicksort
Quicksort, published by C. A. R. Hoare in 1962, is usually faster still. It picks one element, the pivot, moves the smaller elements before it and the others after it, and then sorts the two parts in the same way. The book uses it as its example of recursion.
#include <stdio.h>
int swap(v, i, j) /* exchange v[i] and v[j] */
int v[];
int i, j;
{
int temp;
temp = v[i];
v[i] = v[j];
v[j] = temp;
return 0;
}
/* sort v[left]...v[right] into increasing order */
int quicksort(v, left, right)
int v[];
int left, right;
{
int i, last;
if (left >= right) /* fewer than two elements */
return 0;
swap(v, left, (left + right) / 2); /* the pivot to v[left] */
last = left;
for (i = left + 1; i <= right; i++)
if (v[i] < v[left])
swap(v, ++last, i);
swap(v, left, last); /* the pivot to its place */
printf("v[%d..%d]: pivot %d placed at %d\n",
left, right, v[last], last);
quicksort(v, left, last - 1);
quicksort(v, last + 1, right);
return 0;
}
int main()
{
static int v[] = { 31, 4, 15, 9, 26, 5, 3, 58, 97, 23 };
int i;
quicksort(v, 0, 9);
for (i = 0; i < 10; i++)
printf("%d ", v[i]);
printf("\n");
return 0;
}
quicksort sorts the part of the array between
left and right. A part with fewer than two
elements is already sorted, which ends the recursion. The middle element
becomes the pivot and is moved to v[left]. The loop moves
each smaller element to the front, where last marks the end
of the smaller ones, and the pivot is then swapped to
v[last], which is its final place. The two parts on either
side are sorted by recursive calls. The program prints each part it
splits and where its pivot ends.
$ gcc -std=c89 -pedantic -Wall -Wextra -o quick quick.c $ ./quick v[0..9]: pivot 26 placed at 6 v[0..5]: pivot 15 placed at 4 v[0..3]: pivot 4 placed at 1 v[2..3]: pivot 9 placed at 3 v[7..9]: pivot 97 placed at 9 v[7..8]: pivot 31 placed at 7 3 4 5 9 15 23 26 31 58 97
Binary search
A sorted array can be searched quickly. The binary search compares the value with the middle element and then continues in the half where the value must be, so each step halves the part that is left.
#include <stdio.h>
int nprobes; /* elements looked at by the last search */
/* find x in the sorted v[0]...v[n-1]; return its index or -1 */
int binsearch(x, v, n)
int x;
int v[];
int n;
{
int low, high, mid;
low = 0;
high = n - 1;
nprobes = 0;
while (low <= high) {
mid = (low + high) / 2;
nprobes++;
if (x < v[mid])
high = mid - 1;
else if (x > v[mid])
low = mid + 1;
else
return mid;
}
return -1;
}
int main()
{
static int v[] = { 3, 4, 5, 9, 15, 23, 26, 31, 58, 97 };
static int keys[] = { 3, 26, 97, 10, 100 };
int i, pos;
for (i = 0; i < 5; i++) {
pos = binsearch(keys[i], v, 10);
printf("%3d: index %2d after %d probes\n", keys[i], pos, nprobes);
}
return 0;
}
low and high bound the part of the array where
x can still be. If x is smaller than the middle
element, the upper half is dropped, and if it is larger, the lower half.
When the bounds cross, the value is not in the array, and the function
returns -1. The counter of probes is read after the call: the arguments
of printf can be evaluated in any order, so the call must
not be one of them.
$ gcc -std=c89 -pedantic -Wall -Wextra -o binary binary.c $ ./binary 3: index 0 after 3 probes 26: index 6 after 4 probes 97: index 9 after 4 probes 10: index -1 after 4 probes 100: index -1 after 4 probes
Ten elements need at most four probes, and a thousand would need at most ten: the number grows with the logarithm of the size. A search that looks at every element in turn needs up to ten probes for ten elements and a thousand for a thousand.
The library's qsort
The UNIX library has a sort function, qsort. It sorts an
array of any type, so it needs four arguments: the address of the array,
the number of elements, the size of one element, and a comparison
function. The comparison function receives pointers to two elements and
returns a negative number, zero, or a positive number, as
strcmp does.
#include <stdio.h>
#include <stdlib.h>
/* compare two ints for qsort: negative, zero, or positive */
int up(a, b)
char *a, *b;
{
int x, y;
x = *(int *) a;
y = *(int *) b;
return (x > y) - (x < y);
}
int down(a, b)
char *a, *b;
{
return up(b, a);
}
int show(v, n)
int v[];
int n;
{
int i;
for (i = 0; i < n; i++)
printf("%d ", v[i]);
printf("\n");
return 0;
}
int main()
{
static int v[] = { 31, 4, 15, 9, 26, 5, 3, 58, 97, 23 };
qsort((char *) v, 10, sizeof v[0], up);
show(v, 10);
qsort((char *) v, 10, sizeof v[0], down);
show(v, 10);
return 0;
}
qsort knows nothing about the type of the elements, so it
passes char pointers to the comparison function, which
converts them back with a cast. up returns
(x > y) - (x < y), which is -1, 0, or 1. Returning
x - y would be shorter, but the subtraction can overflow
for large values of different signs. down reverses the order
by swapping the arguments. The function
pointers article explains how a function is passed as an
argument.
$ gcc -std=c89 -pedantic -Wall -Wextra -o libsort libsort.c $ ./libsort 3 4 5 9 15 23 26 31 58 97 97 58 31 26 23 15 9 5 4 3
Searching with bsearch
The C library of Linux also has a binary search,
bsearch. It takes a pointer to the value to look for and
then the same arguments as qsort, and it returns a pointer
to the element found, or NULL.
#include <stdio.h>
#include <stdlib.h>
int up(a, b)
char *a, *b;
{
int x, y;
x = *(int *) a;
y = *(int *) b;
return (x > y) - (x < y);
}
int main()
{
static int v[] = { 3, 4, 5, 9, 15, 23, 26, 31, 58, 97 };
static int keys[] = { 26, 10 };
int i, *p;
for (i = 0; i < 2; i++) {
p = (int *) bsearch((char *) &keys[i], (char *) v, 10,
sizeof v[0], up);
if (p != NULL)
printf("%d found at index %d\n", keys[i], (int) (p - v));
else
printf("%d not found\n", keys[i]);
}
return 0;
}
The value is passed by its address, so the comparison function receives
two pointers of the same kind and up can be reused. The
index of the element is the difference between the returned pointer and
the start of the array.
$ gcc -std=c89 -pedantic -Wall -Wextra -o libsearch libsearch.c $ ./libsearch 26 found at index 6 10 not found
The V7 library has qsort, but not bsearch; it
was added to the library later. The PDP-11 compiler accepts the call to
an undeclared function, and the loader reports the missing name. It
writes C names with a leading underscore. It also lists
_end, the end of the program, a name that it normally
defines itself. On V7, the
binsearch of the previous section is the way to search.
$ cc libsearch.c Undefined: _bsearch _end
Sorting records
A comparison function makes qsort sort anything, including
an array of structures. Each comparison function looks at another member,
so the same array can be sorted by different keys.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct lang {
char *l_name;
int l_year; /* year of the first report or compiler */
};
struct lang langs[] = {
{ "Pascal", 1970 },
{ "Fortran", 1957 },
{ "Modula-2", 1978 },
{ "C", 1972 },
{ "Lisp", 1958 },
{ "Algol 68", 1968 },
{ "Algol 60", 1960 }
};
#define NLANG (sizeof langs / sizeof langs[0])
int byname(a, b)
char *a, *b;
{
return strcmp(((struct lang *) a)->l_name,
((struct lang *) b)->l_name);
}
int byyear(a, b)
char *a, *b;
{
int x, y;
x = ((struct lang *) a)->l_year;
y = ((struct lang *) b)->l_year;
return (x > y) - (x < y);
}
int show(title)
char *title;
{
struct lang *p;
printf("%s:\n", title);
for (p = langs; p < langs + NLANG; p++)
printf(" %-9s %d\n", p->l_name, p->l_year);
return 0;
}
int main()
{
qsort((char *) langs, NLANG, sizeof langs[0], byname);
show("by name");
qsort((char *) langs, NLANG, sizeof langs[0], byyear);
show("by year");
return 0;
}
The elements are struct lang structures. Each comparison
function converts its arguments to pointers to the structure and
compares a member: byname with strcmp and
byyear as numbers. qsort moves the whole
structures, sizeof langs[0] bytes at a time. Upper-case
letters come before lower-case ones in ASCII, so "C" is
sorted before "Fortran" but would also come before
"awk".
$ gcc -std=c89 -pedantic -Wall -Wextra -o records records.c
$ ./records
by name:
Algol 60 1960
Algol 68 1968
C 1972
Fortran 1957
Lisp 1958
Modula-2 1978
Pascal 1970
by year:
Fortran 1957
Lisp 1958
Algol 60 1960
Algol 68 1968
Pascal 1970
C 1972
Modula-2 1978
Source
Dennis Ritchie: C Reference Manual (1975)
In this article we have sorted and searched in K&R C: insertion sort,
Shell sort, a count of the comparisons of both, the recursive quicksort,
binary search, the library's qsort with comparison
functions, bsearch, which the PDP-11 library does not have,
and sorting an array of structures by different keys. The
text processing article sorts lines.
The next article builds linked lists.
Author
List all K&R C tutorials.