Insertion Sort algorithm Program in C

Before you start with the program, you should first learn the charactristics of Insertion Sort algorithm.

Insertion sort algorithm characteristics

  1. Insertion Sort Algorithm space complexity is less. More like a Bubble sort algorithm, Insertion Sort Algorithm requires only a single memory space.
  2. Insertion Sort algorithm is only efficient with smaller datasets.
  3. Insertion Sort algorithm is better then Bubble sort and Selection sort.
  4. If the provided array is partially sorted, then it works more efficiently. It also ignores the similar elements while changing order.

Following is the source code for the insertion type sorting in Arrays . Copy the whole source code and save it in notepad with the extension either *.c or * .cpp. Then open the saved file with your compiler and run the program.
#include<stdio.h>
#include<conio.h>

int main()
{

    int a[100],n,k,i,j,temp;

    printf("Enter the no. of elements you want to enter :\n");

    scanf("%d",&n);

    printf("Enter the %d elements:\n",n);

        for(i=0;i<=n-1;i++)
        {
            scanf("%d",&a[i]);
        }

        for(k=1;k<=n-1;k++)
        {
            temp=a[k];
            j=k-1;


            while(temp<a[j]&&j>=0)
            {
                a[j+1]=a[j];
                j=j-1;
            }

            a[j+1]=temp;
        }

    printf("Elements of array after sorting are :");

        for(i=0;i<=n-1;i++)
        {
            printf("%2d",a[i]);
        }

    getch();

}
AA

Post a Comment

0 Comments