Insertion sort works in the similar way as we sort cards in our hand in a card game.
We assume that the first card is already sorted then, we select an unsorted card. If the unsorted card is greater than the card in hand, it is placed on the right otherwise, to the left. In the same way, other unsorted cards are taken and put at their right place.
A similar approach is used by insertion sort.
Insertion sort is a sorting algorithm that places an unsorted element at its suitable place in each iteration.
How Insertion Sort Works?
Suppose we need to sort the following array.
- The first element in the array is assumed to be sorted. Take the second element and store it separately in
key
.
Comparekey
with the first element. If the first element is greater thankey
, then key is placed in front of the first elemet. - Now, the first two elements are sorted.
Take the third element and compare it with the elements on the left of it. Placed it just behind the element smaller than it. If there is no element smaller than it, then place it at the begining of the array. - In a similar way, place every unsorted element at its correct position.
#include <stdio.h>
void printArray(int array[], int size)
{
for (int i = 0; i < size; i++)
{
printf("%d ", array[i]);
}
printf("\n");
}
void insertionSort(int array[], int size)
{
for (int step = 1; step < size; step++)
{
int key = array[step];
int j = step - 1;
while (key < array[j] && j >= 0)
{
// For descending order, change key<array[j] to key>array[j].
array[j + 1] = array[j];
--j;
}
array[j + 1] = key;
}
}
int main()
{
int data[] = {9, 5, 1, 4, 3};
int size = sizeof(data) / sizeof(data[0]);
insertionSort(data, size);
printf("Sorted array in ascending order:\n");
printArray(data, size);
}
Comments
Post a Comment