C program for Insertion Sort.

insertion-sort.c

Here is a C program to sort the elements of the array in ascending order using a technique called Insertion Sort.

#include<stdio.h>
#include<conio.h>

#define SIZE 10

void insertion_sort(int unsorted_array[], int sorted_array[]);

void main()
{
	int i,j;
	int array_to_sort[SIZE], sorted_array[SIZE];
	clrscr();

	//Get the elements of Array
	for(i=0; i<SIZE; i++)
	{
		j = i+1;
		printf("\nEnter element %d: ",j);
		scanf("%d", &array_to_sort[i]);
	}

	//Print the unsorted array.
	printf("\n\nUnsorted elements of Array are: ");	
	for(i=0; i<SIZE; i++)
	{
		printf("%d ",array_to_sort[i]);
	}

	//Sort array.
	insertion_sort(array_to_sort, sorted_array);

	//Print the sorted array.
	printf("\n\nSorted elements of Array are: ");	
	for(i=0; i<SIZE; i++)
	{
		printf("%d ",sorted_array[i]);
	}

	getch();
}

//Logic for Insertion Sort.
void insertion_sort(int unsorted_array[], int sorted_array[])
{
	int i, j, key, location;

	sorted_array[0] = unsorted_array[0];

	for(i=1; i<SIZE; i++)
	{
		//Pick the element
		key = unsorted_array[i];

		//Find appropriate location by comparison
		location = i;
		while((location > 0) && (key < sorted_array[location-1]))
		{
			location = location - 1;
		}

		//Shift elements if required
		j = i;
		while(j > location)
		{
			sorted_array[j] = sorted_array[j-1];
			j = j-1;
		}

		//Place the element
		sorted_array[location] = key;
	}
}