student@ubuntu:~$
c 3/5 30 XP

Sorting

0%

Quick Reference

Selection sort (Dr. Steiner’s preferred algorithm):

void selection_sort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        int min_idx = i;
        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[min_idx])
                min_idx = j;
        }
        int temp = arr[min_idx];
        arr[min_idx] = arr[i];
        arr[i] = temp;
    }
}

qsort usage:

int compare(const void *a, const void *b) {
    return *(int *)a - *(int *)b;
}
qsort(arr, n, sizeof(int), compare);

Common Pitfalls

  • Off-by-one in outer loop – Outer loop goes to n - 1, not n. The last element is already sorted.
  • Forgetting to cast in qsort – void pointers must be cast before dereferencing. *a alone won’t compile.
  • Integer overflow in comparea - b can overflow for large values. Safer: return (a > b) - (a < b);.

Unlocks

Complete this skill to see what it unlocks.