Arrays and algorithms · intermediate
C Program for Bubble Sort
Sort an array with bubble sort in C, stop early when a pass makes no swaps, and compare it with the standard library's qsort() and a comparison function.
- nested loops
- swapping
- early exit flag
- qsort() with a comparator
Bubble sort repeatedly compares neighbouring elements and swaps them when they are out of order. After each pass the largest remaining element has moved to the end. It takes about n²/2 comparisons, so it is slow for big arrays, but it is the standard first sorting algorithm because every step is easy to follow.
The program
#include <stdbool.h>
#include <stdio.h>
void bubble_sort(int *a, int n) {
for (int end = n - 1; end > 0; end--) {
bool swapped = false;
for (int i = 0; i < end; i++) {
if (a[i] > a[i + 1]) {
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
swapped = true;
}
}
if (!swapped)
break;
}
}
int main(void) {
int data[] = {5, 1, 4, 2, 8};
int n = sizeof data / sizeof data[0];
bubble_sort(data, n);
for (int i = 0; i < n; i++)
printf("%d ", data[i]);
printf("\n");
return 0;
}1 2 4 5 8 How it works
- end marks the last position of the unsorted part; it moves one place left after each pass.
- The inner loop compares a[i] with a[i + 1] and swaps them through a temporary variable when a[i] is bigger.
- swapped records whether the pass changed anything; a pass with no swaps means the array is sorted, so the loop stops early.
- The function sorts the caller's array directly, because the array is passed as a pointer.
Another way: qsort() from the standard library
qsort() sorts any array given a comparison function that returns a negative, zero or positive value. (x > y) - (x < y) avoids the overflow that x - y can cause.
#include <stdio.h>
#include <stdlib.h>
int compare_ints(const void *p, const void *q) {
int x = *(const int *)p, y = *(const int *)q;
return (x > y) - (x < y);
}
int main(void) {
int data[] = {5, 1, 40, 2, 8};
qsort(data, 5, sizeof data[0], compare_ints);
for (int i = 0; i < 5; i++)
printf("%d ", data[i]);
printf("\n");
return 0;
}1 2 5 8 40 Common mistakes
- Running the inner loop to i < n, so a[i + 1] reads past the end of the array.
- Writing the comparator as return x - y; it overflows for values far apart, such as INT_MIN and 1.
- Swapping without a temporary (a[i] = a[i + 1]; a[i + 1] = a[i];), which duplicates one value.
Try it yourself
- Count swaps and comparisons for a sorted, a reversed and a random array.
- Sort in descending order by changing one comparison.
Open the program in the C Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 C examples, or write your own program in the online C Compiler.