</>EmbeddedInterview

Implement selection sort.

Easy"Coding: Sorting & Array Problems"
#include <stddef.h>

void selection_sort(int *a, size_t n)
{
    for (size_t i = 0; i + 1 < n; i++) {
        size_t min = i;
        for (size_t j = i + 1; j < n; j++)
            if (a[j] < a[min]) min = j;
        if (min != i) { int t = a[i]; a[i] = a[min]; a[min] = t; }
    }
}

Points: always O(n²) comparisons but at most n − 1 swaps, which matters when writes are expensive (e.g. sorting records stored in flash or EEPROM). Not stable in this form, in place.