← The C Language Lesson 71 of 77 · 10 XP

Sorting

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

Insertion sort is a simple and clear algorithm. It's how you sort cards in your hand: take the next item and move it to the left until it's in its place.

void insertion_sort(int *a, int n)
{
    for (int i = 1; i < n; i++) {
        int key = a[i];
        int j = i - 1;
        while (j >= 0 && a[j] > key) {
            a[j + 1] = a[j];     // move the bigger one to the right
            j--;
        }
        a[j + 1] = key;
    }
}

On almost sorted data it's very fast, but in the worst case it makes about n²/2 comparisons. On a million items that already takes a long time.

Fast algorithms (quicksort, mergesort) work in n·log n. In C, a ready-made one is in the standard library:

int cmp(const void *x, const void *y)
{
    int a = *(const int *)x, b = *(const int *)y;
    return (a > b) - (a < b);    // -1, 0 or 1 with no risk of overflow
}
qsort(a, n, sizeof a[0], cmp);

Task. Implement insertion_sort yourself (without qsort) and print the sorted array separated by spaces.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.