Kodewick
Start learning →
Basic←→0 / 50

Bubble sort

#033Basica[j] > a[j + 1]8 min

Use bubble sort to put an array in order from small to big: each pass goes from start to end, comparing neighbours, and swaps them if the first is bigger than the second. Each pass, the biggest number "bubbles up" to the end. Finish bubble_sort(a, n); the program sorts two arrays and shows them.

Should show
1 2 5 7 9
-1 0 3 3
main.c
#include <stdio.h>

void bubble_sort(int a[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - 1 - i; j++) {
            // your code here: if the first is bigger than the next, swap them
        }
    }
}

void show(int a[], int n) {
    for (int i = 0; i < n; i++) printf(i ? " %d" : "%d", a[i]);
    printf("\n");
}

int main(void) {
    int a[] = {5, 2, 9, 1, 7};
    int b[] = {3, 3, -1, 0};
    bubble_sort(a, 5);
    bubble_sort(b, 4);
    show(a, 5);
    show(b, 4);
    return 0;
}
Ctrl + Enter runs too
Result

Run tries the examples. When they look right, Submit.