Sunday, 27 September 2015

Insertion sorting

Today we will be talking abut insertion sort . This is a very simple program but an important algorithm for sorting the numbers . The approach is quite similar to sorting of playing cards . when we find a new number we will move that card there and will shift the other cards.
here is the program

       #include<stdio.h>
void main()
{
    int A[]= {12,65,32,87,98,21,43,14,65,76};
    int size= sizeof(A)/ sizeof(A[0]) ;        /*it will give number of elements*/
    insertion_sort(A,size);
    output(A,size);

}
void insertion_sort(int *A,int size)
{
    int i ,j;
    for (i=1;i<size;i++)                   /*as last index=size-1*/
    {
        int key =A[i];
        j=i-1;
        while (A[j]>key&&j>0)      /* loop will go on and on & swaps until A[j] is smaller than key */
        {
            A[j+1]=A[j];
            j--;
        }
        A[j+1]=key;
    }
}

void output(int *A,int size)
{
    int i=0;
    for(i=0;i<size;i++)
    {
        printf("%d\n",A[i]);

    }
}

No comments:

Post a Comment