Skip to content
Laviyx Learn

Try

PPS Lab · Experiment 46

Insertion sort

CSorting and searchingJNTUH R22 · CS108ES

Aim

To write a C program that sorts an array of integers in ascending order using insertion sort, and shows the array after each pass.

Algorithm

  1. Read n (1 to 100) and then n integers into an array.
  2. Repeat for i = 1 to n − 1. The elements a[0..i−1] are already sorted.
  3. Save a[i] in key.
  4. Set j = i − 1. While j ≥ 0 and a[j] is greater than key, move a[j] one place to the right (to a[j + 1]) and decrease j by 1.
  5. Put key in the gap at a[j + 1].
  6. Print the array after the pass.
  7. Print the sorted array.

Program

C
#include <stdio.h>

#define MAX 100

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

/* Sorts a[0..n-1] in ascending order, printing the array after each pass */
void insertion_sort(int a[], int n) {
    for (int i = 1; i < n; i++) {
        int key = a[i];
        int j = i - 1;
        /* Move larger elements of the sorted part one place to the right */
        while (j >= 0 && a[j] > key) {
            a[j + 1] = a[j];
            j--;
        }
        a[j + 1] = key;     /* put key in the gap */
        printf("After pass %d: ", i);
        print_array(a, n);
    }
}

int main(void) {
    int a[MAX], n;

    printf("Enter the number of elements (1 to %d): ", MAX);
    if (scanf("%d", &n) != 1 || n < 1 || n > MAX) {
        printf("Invalid number of elements\n");
        return 1;
    }
    printf("Enter %d integers: ", n);
    for (int i = 0; i < n; i++) {
        if (scanf("%d", &a[i]) != 1) {
            printf("Invalid input\n");
            return 1;
        }
    }

    insertion_sort(a, n);
    printf("Sorted list: ");
    print_array(a, n);
    return 0;
}

Output

Output
Enter the number of elements (1 to 100): 6
Enter 6 integers: 38 27 43 3 9 10
After pass 1: 27 38 43 3 9 10 
After pass 2: 27 38 43 3 9 10 
After pass 3: 3 27 38 43 9 10 
After pass 4: 3 9 27 38 43 10 
After pass 5: 3 9 10 27 38 43 
Sorted list: 3 9 10 27 38 43 

Recorded by compiling and running this exact program. Typed input appears after each prompt.

How it works

Insertion sort works the way many people sort playing cards in their hand: pick up the next card and slide it left into its place among the cards already sorted.

In pass 2 of the run, 43 is already bigger than 38, so the while loop does not move anything and the array stays the same. In pass 3, 3 is smaller than every sorted number, so 43, 38 and 27 each move one place right and 3 goes to the front.

Common mistakes

  • Writing the while condition as a[j] > key && j >= 0. When j becomes −1, a[-1] is read before the j >= 0 check. Put j >= 0 first, so && stops before reading a[-1].

  • Comparing with a[i] inside the while loop instead of key. After the first shift, a[i] has already been overwritten. Save it in key before shifting.

  • Putting key at a[j] instead of a[j + 1]. When the loop stops, j points to the element just before the gap, so the gap is at j + 1.

  • Starting the outer loop at i = 0. A single element is already sorted, so the first element to insert is a[1].

Viva questions

Try to answer each one aloud before you open it.

  • How does insertion sort work?

    It keeps the left part of the array sorted. In each pass it takes the next element and moves it left, shifting larger elements right, until it reaches its correct place in the sorted part.

  • What is the time complexity of insertion sort?

    O(n²) in the worst and average cases, for example when the list is in reverse order. The best case is O(n), when the list is already sorted, because no shifts are needed.

  • When is insertion sort a good choice?

    For small lists, and for lists that are already nearly sorted, because then each element moves only a short distance.

  • Is insertion sort stable?

    Yes. An element moves left only past elements that are strictly greater (a[j] > key), so equal elements keep their original order.

  • Why is key saved before the while loop?

    The shifting overwrites a[i] with a[i - 1]. Without saving it, the value to insert would be lost.

Learn the concepts

All Programming for Problem Solving Lab experiments →