Insertion sort is an algorithm used to sort a collection of elements in ascending or descending order. The basic idea behind the algorithm is to divide the list into two parts: a sorted part and an unsorted part.Insertion sort is a sorting algorithm that places an unsorted element at its suitable place in each iteration.
Suppose we need to sort the following array.
1.The first element in the array is assumed to be sorted. Take the second element and store it separately in key.Compare key with the first element. If the first element is greater than key, then key is placed in front of the first element.
2.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 beginning of the array.
3.Similarly, place every unsorted element at its correct position.
To sort an array of size N in ascending order:
- Iterate from arr[1] to arr[N] over the array.
- Compare the current element (key) to its predecessor.
- If the key element is smaller than its predecessor, compare it to the elements before. Move the greater elements one position up to make space for the swapped element.
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int InsertionSort(int a[], int array_size)
{
int i,j,small;
for(i=1;i<array_size;i++)
{
small=a[i];
for(j=i-1;j>=0 && small<a[j];j--)
{
a[j+1]=a[j];
}
a[j+1]=small;
}
printf("\nSorted Data :");
for (i = 0; i < array_size; i++) {
printf("\t%d", a[i]);
}
}
int main()
{
int ret,element;
int arr[5]={32,5,7,3,72};
InsertionSort(arr,5);
if(ret==-1)
{
printf("Element not found!");
}
}