DATA STRUCTURES



Admission Enquiry Form

Insertion sort in an Array.

In insertion sort the array is split into two sub-list sorted sub-list and unsorted sub-list. Values from the unsorted sub-list are picked and placed at the correct position in the sorted sub-list.


Example




Program of Insertion Sort in an Array.

#include<stdio.h>

void insertsort(int arr[],int n) /* function to sort an arrayy with insertion sort */
{
int i,j,temp;
for (i=1;i<n;i++)
{
temp=arr[i];
j=i-1;

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

void printarray(int arr[], int n) /* function to print the array */
{
int i;
for(i=0;i<n;i++)
{
printf("%d ",arr[i]);
}
}

void main()
{
int arr[]={ 4,3,2,10,12,1,5,6};
int n=sizeof(arr)/sizeof(arr[0]);
printf("Before sorting array elements are: \n");
printarray(arr,n);
insertsort(arr,n);
printf("\nAfter sorting array elements are: \n");
printarray(arr,n);
}