Insertion Sort

Algorithm

Input	Array of integers 
Output	Sorted array
Complexity	O(n^2).

Insertion_sort(a,n)
1.	Set n=Input size of array;
2.	Repeat steps 4-10 for i=1 to n
3.	Set temp = a[i];
4.	Set j = i-1;
5.	Repeat steps 7-9  while( temp<a[j])
6.	Set a[j+1] = a[j];
7.	[decrease j] j= j-1;
8.	If (j==-1) then:  break;
9.	[end of while loop]
10.	Set a[j+1] = temp;
11.	[end of for loop]
12.	[end]

Algorithm Description


C Code

#include<stdio.h>
#include<conio.h>
int main()
{
	int a[10],i,j,k,temp,n;
	printf("enter the no. of elements\n");
	scanf("%d",&n);
	printf("enter %d elements\n",n);
	for(i=0;i<n;i++)
	scanf("%d",&a[i]);
	for(i=1;i<n;i++)
	{
		temp=a[i];
		j=i-1;
		while(temp<a[j] && j>=0)
		{
			a[j+1]=a[j];
			j--;
		}
		if(j!=i-1)
			a[j+1]=temp;
	}
	printf("Sorted array is : \n");
	for(i=0;i<n;i++)
		printf("%d \n",a[i]);
	return 0;
}


Java Code

import java.io.*;
class insertion
{
	public static void main(String args[]) throws Exception
	{
		int temp,n,i,j,k,temp1;
		BufferedReader cin= new BufferedReader (new InputStreamReader(System.in));
		System.out.println("enter the no. of elements");
		n=Integer.parseInt(cin.readLine());
		int arr[]=new int[n];
		System.out.println("enter the elements to be sorted");
		for(i=0;i<n;i++)
		{
			arr[i]= Integer.parseInt(cin.readLine());
		}
                                for(k=1;k<n;k++)
		{
			temp=arr[k];
			j=k-1;
			while(j>=0 && temp<arr[j] )
			{	
				temp1=arr[j];
				arr[j]=arr[j+1];
				arr[j+1]=temp1;
				j=j-1;
			}
			 arr[j+1]=temp;
		}
            System.out.println("the elements after sorting are:");
		for(i=0;i<n;i++)
			System.out.println(arr[i]); 
	}
}