RUN

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.

main.c

#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

Open the full C online compiler →