NEW AND EXCLUSIVE : GO TO THE ONLINE TEST PAGE AND TEST YOURSELF THROUGH EXAMINATION

Logic Of Insertion Sort

In insertion sort, sorting is done by inserting a particular element at the appropriate position.
In the First iteration, second element A[1] is compared with the first element A[0]. In the second iteration third element is compared with first and second element. Actually in every iteration an element is compared with all the elements before it. While comparing if it is found that the element can be inserted at a suitable position, then space is created for it by shifting the other elements one position up and inserts the desired element at the suitable position. This procedure is repeated for all the elements in the list untill we get the ultimate sorted elements.


Here is a pictorial representation of logic of Insetion sort:
















Program in C: 

for sorting elements in ascending order




#include<stdio.h>
#include<conio.h>
void main()
{
int A[20], N, Temp, i, j;
clrscr();
printf("ENTER THE NUMBER OF TERMS:  ");
scanf("%d", &N);
printf("\n ENTER THE ELEMENTS OF THE ARRAY:  ");
for(i=0; i<N; i++)
{
gotoxy(25,11+i);
scanf("\n\t\t%d", &A[i]);
}
for(i=1; i<N; i++)
{
Temp = A[i];
j = i-1;
while(Temp<A[j] && j>=0)
{
A[j+1] = A[j];
j = j-1;
}
A[j+1] = Temp;
}
printf("\n\THE ASCENDING ORDER IS LIKE THIS:  ");
for(i=0; i<N; i++)
printf("\n\t\t\t%d", A[i]);
getch();
}



Let me learn what you think :)