Home › C Tutorial › C sorting (DSA)
C sorting (DSA)
Bubble sort.
Bubble sort swaps neighbours that are out of order. It is simple but slow (O(n squared)). Real code uses qsort.
Example code
#include <stdio.h>
int main() {
int a[] = {5, 2, 9, 1}, n = 4;
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - 1 - i; j++)
if (a[j] > a[j + 1]) { int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t; }
for (int i = 0; i < n; i++) printf("%d ", a[i]);
printf("\n");
return 0;
}