Welcome

C Programming Tutorial


C Sorting Algorithms - Insertion Sorting

Algorithm

  • Find the minimum element in an Array
  • Swap it with the value in the current position
  • repeat the above process for all element

Insertion Sorting Complete C Program

/******************************************************************************************
*
*                     This Program Performs Insertion Sorting
*
******************************************************************************************/	
#include <stdio.h>

void display(int *,int);
void InsertionSort(int*a,int);

int main()
{
        int a[]={6, 8, 1, 4, 5, 3, 7, 2};

        int n=sizeof(a)/sizeof(a[0]);

        InsertionSort(a,n); printf("\n");

return 0;
}

void InsertionSort(int*a,int n){

        for(int i=1; i < n; i++)
        {
                int j=i;

                for(int k=0; k < j && j < n; k++)
                {
                        if(a[j] < a[k])
                        {
                        	//printf("i=%d j=%d k=%d\n",i,j,k);
                        	int t=a[k];
                        	a[k]=a[j];
                        	a[j]=t;
                        }

                }
              display(a,n);
        }
}
void display(int *a,int n)
{
        for(int i=0; i < n; i++)
           printf("%d ",a[i]);
        printf("\n");
}

	
Output: in Each Iteration
6 8 1 4 5 3 7 2 
1 6 8 4 5 3 7 2 
1 4 6 8 5 3 7 2 
1 4 5 6 8 3 7 2 
1 3 4 5 6 8 7 2 
1 3 4 5 6 7 8 2 
1 2 3 4 5 6 7 8 

Time and Space Complexity

Space:
Time:

ADS