How to Insertion Sort in C – Best C Programming Course

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

Free C Programming Course · Arrays

Insertion Sort in C

Understand insertion sort in C with a clear trace, a tested program and a comparison against bubble sort and selection sort. Free C tutorial for embedded systems learners.

Insertion sort in C works the way most people sort playing cards in their hand: pick up the next card and slide it into the correct place among the cards you already hold. In this lecture of our free C programming course you will turn the “insert into a sorted array” idea from the previous lecture into a complete sorting program. You will trace it on paper, run it, compare it with the other sorts you have learned, and see why embedded C programming often prefers it for small or nearly sorted data.

What You Will Learn

  • The core idea of insertion sort in C: a growing sorted prefix
  • How the key, the inner shifting loop and the final placement fit together
  • How to trace insertion sort and count the shifts
  • Why the number of shifts equals the number of out-of-order pairs
  • How insertion sort compares with bubble sort and selection sort
  • When insertion sort is the right choice in firmware

Prerequisites

  • The previous lecture: inserting an element in a sorted array
  • Bubble sort and selection sort basics from earlier in this chapter
  • Array indexing and while loops

Insertion Sort in C: The Core Idea

Split the array into two regions. The left region is sorted. The right region is unsorted. At the start the sorted region contains just the first element, because a single item is trivially in order. Then repeat: take the first element of the unsorted region (call it the key), insert it into the sorted region at its correct position, and the sorted region grows by one. When the unsorted region is empty, you are done.

Loop invariant

Before each step with key index k, the elements at indexes 0 to k-1 are sorted. After the step, indexes 0 to k are sorted. When k reaches the array length, the whole array is sorted.

Insertion Sort Step by Step

Let us sort seven values: 34 8 51 3 27 15 42. The diagram shows the array after each key has been inserted. The bright chip is the key that was just placed, the pale chips are the sorted region, and the blue chips are still waiting.

Insertion sort in C: sorted region grows one key at a time
Legend
sorted regionkey just insertednot yet visited
Input
348513271542
Key 8
834513271542
Key 51
834513271542
Key 3
383451271542
Key 27
382734511542
Key 15
381527345142
Key 42
381527344251
KeyItems shifted rightWhere the key lands (index)
81 (34)0
5102 (stays put)
33 (51, 34, 8)0
272 (51, 34)2
153 (51, 34, 27)2
421 (51)5

Total shifts: 1 + 0 + 3 + 2 + 3 + 1 = 10. That number is not an accident. Each shift fixes exactly one pair of elements that were in the wrong order, so the total number of shifts equals the number of such “inverted” pairs in the input. A nearly sorted array has few inverted pairs, which is why insertion sort is quick on it.

Insertion Sort in C: Complete Program

#include <stdio.h>

#define N 7

static void print_array(const int a[], int n)
{
    for (int i = 0; i < n; i++)
        printf("%3d", a[i]);
    printf("\n");
}

int main(void)
{
    int data[N] = {34, 8, 51, 3, 27, 15, 42};

    printf("Input     :");
    print_array(data, N);

    for (int k = 1; k < N; k++) {
        int key = data[k];
        int i = k - 1;

        while (i >= 0 && data[i] > key) {
            data[i + 1] = data[i];
            i--;
        }
        data[i + 1] = key;

        printf("Key %2d    :", key);
        print_array(data, N);
    }

    printf("Sorted    :");
    print_array(data, N);
    return 0;
}

Understanding each part

  • for (int k = 1; ...) starts at 1 because index 0 alone is already a sorted region of size one.
  • int key = data[k]; saves the value, because the slot k will be overwritten by a shift.
  • int i = k - 1; points to the last element of the sorted region.
  • The while loop shifts every element greater than key one place right and walks left. Note i >= 0 is tested first.
  • data[i + 1] = key; writes the key into the gap that the shifting opened.
  • The printf inside the loop is only for learning. Remove it in production code.

Build and run

gcc -Wall -Wextra -std=c11 -o insertion_sort insertion_sort.c
./insertion_sort

Expected output:

Input     : 34  8 51  3 27 15 42
Key  8    :  8 34 51  3 27 15 42
Key 51    :  8 34 51  3 27 15 42
Key  3    :  3  8 34 51 27 15 42
Key 27    :  3  8 27 34 51 15 42
Key 15    :  3  8 15 27 34 51 42
Key 42    :  3  8 15 27 34 42 51
Sorted    :  3  8 15 27 34 42 51

Compare each output line with the diagram. For example, the line for key 3 shows 3 jumping all the way to the front, which is exactly the 3 shifts in the table.

Bubble vs Selection vs Insertion Sort

Now that you know three simple sorts, it helps to compare them side by side.

PropertyBubble sortSelection sortInsertion sort
Best case timeO(N) with early-exit flagO(N squared)O(N)
Worst case timeO(N squared)O(N squared)O(N squared)
Extra memoryO(1)O(1)O(1)
Stable (equal items keep order)YesNot in the usual swap versionYes
Data movementMany swapsAt most N – 1 swapsShifts, one write per shift
Fast on nearly sorted inputYes, with flagNoYes, very

Why insertion sort is popular in practice

A shift is one assignment, while a bubble-sort swap is three. Insertion sort also does very little when the data is almost in order. For these reasons, many general-purpose sort implementations hand tiny sub-ranges to an insertion-sort style routine.

Real-World Uses in Embedded C

  • Streaming data: when samples arrive one at a time, you can keep them sorted using the insert function and never run a full sort.
  • Small tables: sorting a 16-entry configuration or calibration table at start-up.
  • Nearly sorted logs: re-sorting a buffer where only a few timestamps arrived late.
  • Code-size sensitive builds: the algorithm is only a few lines, which suits tiny flash budgets.

Common Mistakes and Troubleshooting

MistakeResultFix
Starting the outer loop at 0Harmless but wastes one iterationStart at 1
Not saving the key before shiftingKey value is overwritten and lostCopy data[k] into key first
Testing data[i] before i >= 0Reads data[-1], undefined behaviourCheck the index first
Using >= in the while testEqual items shift; sort loses stabilityUse >
Writing the key to data[i]Key overwrites an elementWrite to data[i + 1]

Warning: The most frequent beginner bug is the final write position. After the loop, i points at the element that is not greater than the key (or at -1). The gap is always one slot to the right, at i + 1.

Best Practices

  • Wrap the sort in a function that takes the array and its length.
  • Test with sorted, reverse-sorted, all-equal and single-element arrays.
  • Print only while learning; remove debug prints from production firmware.
  • Performance: expect roughly N squared over four shifts for random data, so keep arrays small, or switch algorithms past a few hundred items.
  • Use size_t or a signed index carefully. If you change i to an unsigned type, the test i >= 0 is always true and the loop never ends correctly.

Summary and Key Takeaways

  • Insertion sort in C grows a sorted prefix by inserting one key at a time.
  • The inner loop shifts larger values right; the key is written at i + 1.
  • Total shifts equal the number of out-of-order pairs.
  • Best case O(N), worst case O(N squared), O(1) extra memory, stable.
  • Great for small or nearly sorted arrays, which are common in embedded C programming.

Conclusion

You have built insertion sort in C from the insert-into-sorted-array step you learned earlier and checked it against a hand trace. Together with bubble sort and selection sort, you now have three simple sorting tools and the vocabulary (stable, in place, best case, worst case) to choose between them. In the next lecture you will learn to merge two sorted arrays into a third one, the building block of faster sorting methods.

Frequently Asked Questions

What is insertion sort in C?

It is a sorting algorithm that builds a sorted region at the left of the array by inserting each next element into its correct position.

Is insertion sort faster than bubble sort?

Usually yes. Both have O(N squared) worst cases, but insertion sort does fewer writes and handles nearly sorted data very well.

Why does the outer loop start at index 1?

A single element at index 0 is already a sorted region, so insertion starts with the second element.

Is insertion sort stable?

Yes, when the shifting test uses a strict greater-than comparison.

Does insertion sort work in place?

Yes. It needs only a few extra variables (key and index), so extra memory is O(1).

When should I avoid insertion sort?

For large, randomly ordered arrays. The quadratic cost grows quickly; use qsort or another O(N log N) method instead.

How is insertion sort related to inserting into a sorted array?

Insertion sort performs that insert operation once for every element, using the already sorted left part as the target.

Keep Going with the Free C Tutorial

Next: merging two sorted arrays. Our free embedded C course takes you from first program to firmware-ready skills.

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *