Thursday, January 8, 2009

C code for insertion sort

#include <iostream.h>





void insert(int a[],int i,int j)

{



        //function for inserting ith element at jth position

        int t = a[i];

        int k;

        for (k=i;k>j;k--)

                a[k] = a[k-1];

        a[j] = t;

}



void printArray(int a[])

{

 int k;

 for(k=0;k<10;k++)

         cout << a[k] << " ";

 cout << endl;

}



int main()

{

        int a[10] = {1,3,2,4,8,7,5,10,9,6};

        int i;

        printArray(a);

        for(i=0;i<9;i++)

        {

                if(a[i] > a[i+1])

                {

                        cout << "conflict here" << a[i] << ">" << a[i+1] << endl;

                        //conflict exists

                        //find the appropriate position for i+1 th element

                        int j,pos;

                        for(j=0;j<i+1;j++)

                        {

                           if(a[j] > a[i+1])

                           {

                                   pos = j;

                                   insert(a,i+1,pos);

                                   printArray(a);

                                   break;

                           }

                        }

                                

                }

        }



printArray(a);



}

No comments:

Blog Archive