Saturday 2 August 2014

Insertion Sort

Insertion Sort

The Code provided below is the C-code for bubble sorting technique of an array.

//Insertionsort
#include<stdio.h>
#define MAX 5
void insertionsort(int *,int *);
void display(int *,int *);
int main()
{
    int a[MAX],n,i;
    printf("Enter the no. of elements in the array,where MAX=%d: ",MAX);
    scanf("%d",&n);
    for(;n>MAX;scanf("%d",&n))
    printf("The value entered is greater than MAX.Please re-enter the value: ");
    printf("Enter the elements of the array: \n");
    for(i=0;i<n;i++)
    scanf("%d",&a[i]);
    printf("The unsorted array: ");
    display(a,a+n);
    printf("\n");
    insertionsort(a,a+n);
    printf("The sorted array: ");
    display(a,a+n);
    return 0;
}

void insertionsort(int *p,int *q)
{
    if(p!=q)
    {
        int i,j,temp;
        for(i=1;p+i<q;i++)
        {
            j=i-1;
            temp=*(p+i);
            for(;j>=0 && *(p+j)>temp;j--)
            *(p+j+1)=*(p+j);
            *(p+j+1)=temp;
        }
    }
}

void display(int *p,int *q)
{
    for(;p<q;p++)
    printf("%d ",*p);
}

No comments:

Post a Comment