Sort an array (bubble sort) in C
Sort numbers by swapping neighbours until nothing moves. Press Run to try it, then change the code and run it again.
#include <stdio.h>
int main(void) {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof arr / sizeof arr[0];
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int t = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = t;
}
}
}
for (int i = 0; i < n; i++) printf("%d ", arr[i]);
printf("\n");
return 0;
}
Output
Press Run to see the output.
More C examples
- Hello, World · The classic first C program.
- Sum of two numbers · Read two numbers with scanf and print their sum.
- Check a prime number · Test whether a number is prime by trying divisors up to its square root.
- Pointers: swap two numbers · Pass addresses to a function so it can change the caller’s variables.
- Structs and malloc · Build a small linked list on the heap, print it and free it.