Kodewick
Start learning →
Basic←→0 / 50

Selection sort

#034Basica[j] < a[min]8 min

Sort an array from small to big with selection sort: pass 1 finds the smallest number and swaps it with the 1st; pass 2 finds the smallest of the rest and swaps it with the 2nd, and so on. In the starter, min is the index of the smallest, and the swap is written. Finish selection_sort(a, n).

Should show
11 12 22 25 64
-2 0 1 4 4 7
main.c
#include <stdio.h>

void selection_sort(int a[], int n) {
    for (int i = 0; i < n - 1; i++) {
        int min = i;
        for (int j = i + 1; j < n; j++) {
            // your code here: if a[j] is smaller than the smallest so far, remember j
        }
        int t = a[i];
        a[i] = a[min];
        a[min] = t;
    }
}

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[] = {64, 25, 12, 22, 11};
    int b[] = {4, -2, 4, 0, 7, 1};
    selection_sort(a, 5);
    selection_sort(b, 6);
    show(a, 5);
    show(b, 6);
    return 0;
}
Ctrl + Enter runs too
Result

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