Navigation Menu

Currently the navigation bar is not functioning. Use the Blog Archive or the Google Custom Search to find content.

Thursday 13 June 2013

C program to implement Insertion sort

Given below is a C program to implement Insertion sort.
What is Insertion sort? Click here to read about it.
In Insertion sort the element is positioned at its proper place by inserting it and shifting the other elements to the right. The elements are sorted in increasing order of their position.

Example :
75 35 47 15

Pass 0 : 75 35 47 15
Pass 1 : 35 75 47 15
Pass 2 : 35 47 75 15
Pass 3 : 15 35 47 75

Links that you may find important :

http://www.sorting-algorithms.com/insertion-sort
http://www.algolist.net/Algorithms/Sorting/Insertion_sort
https://www.youtube.com/watch?v=c4BRHC7kTaQ
https://www.youtube.com/watch?v=Kg4bqzAqRBM

Code :
#include <stdio.h>
#include <conio.h>
void insert(int n,int a[])
{
    int i,j,k; 
    for(i=1;i<=n;i++)
    {
        int temp=a[i];
        printf("\nPass %d: ",i);
        for(k=0;k<n;k++)
        {
            printf("%d\t",a[k]);
        }
        for(j=i-1;j>=0;j--)
        {
            if(temp<a[j])
            { 
                a[j+1]=a[j];
                a[j]=temp;
            }
        }
    }
}
void main()
{
    int i,n,a[10];
    clrscr();
    printf("Enter no. of elements : ");
    scanf("%d",&n);
    printf("Enter the elements in array : \n");
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    insert(n,a);//call to function that performs the sorting
    printf("\nElements after sorting\n");
    for(i=0;i<n;i++)
    {
        printf("%d\t",a[i]);
    }
    getch();
}
Output :
Enter no. of elements : 4
Enter the elements in array :
75
35
47
15

Pass 1: 75      35      47      15
Pass 2: 35      75      47      15
Pass 3: 35      47      75      15
Pass 4: 15      35      47      75
Elements after sorting
15      35      47      75
Note : The program above has been tested using TurboCPP. Leave a comment if you feel the program is incorrect and/or has errors and/or if the program and its output don't match. Please report about broken links.

No comments:

Post a Comment