Insertion Sort is a simple comparison-based sorting algorithm that builds the final sorted list one element at a time.
- It divides the list into sorted and unsorted part. Initially, the first element is already considered sorted, while the rest of the list is considered unsorted.
- The algorithm then iterates through each element in the unsorted part, picking one element at a time, and inserts it into its correct position in the sorted part.
- It is easy to implement and works well for small datasets.
Let's take an example of array arr = {12, 11, 13, 5, 6} that we need to sort in ascending order.
Insertion Sort Algorithm in C
- Start with the second element (index 1) as the key.
- Compare the key with the elements before it.
- If the key is smaller than the compared element, shift the compared element one position to the right.
- Insert the key where the shifting of elements stops.
- Repeat steps 2-4 for all elements in the unsorted part of the list.
#include <math.h>
#include <stdio.h>
void insertionSort(int arr[], int N)
{
// Starting from the second element
for (int i = 1; i < N; i++)
{
int key = arr[i];
int j = i - 1;
// Move elements of arr[0..i-1], that are
// greater than key, to one position to
// the right of their current position
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
}
// Move the key to its correct position
arr[j + 1] = key;
}
}
int main()
{
int arr[] = {12, 11, 13, 5, 6};
int N = sizeof(arr) / sizeof(arr[0]);
printf("Unsorted array: ");
for (int i = 0; i < N; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
// Calling insertion sort on array arr
insertionSort(arr, N);
printf("Sorted array: ");
for (int i = 0; i < N; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Output
Unsorted array: 12 11 13 5 6 Sorted array: 5 6 11 12 13
Time Complexity: O(N2)
Auxiliary Space: O(1)
Advantages of Insertion Sort
- Insertion sort is that it is an in-place sorting algorithm.
- It is simple to implement which is great for small datasets.
- Insertion sort is adaptive in nature, i.e. it is appropriate for data sets which are already partially sorted.
- Best-case scenario only requires O(n) time.
Note: The algorithm typically shows only the final sorted result, not the progress after each iteration, making it harder to trace or debug.