Tag Archives: insertionsort c code

Insertion Sort

Insertion sort  is a simple sorting algorithm that iterates through the list consuming one input element each repetition, and growing a sorted output list. On a repetition, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. It repeats until no input elements remain.Sorting is done inplace .So its an inplace sorting algorithm and original order is maintained.For more information on insertion sort visit http://en.wikipedia.org/wiki/Insertion_sort.

Below is the C++ code for insertion sort algorithm.
CODE:

/*
http://randomtechbits.in/
*Program to sort numbers using INSERTION SORT
*inputs: N- number of integers to sort ,A-array of integers
*output: sorted array of integers
*code tested on devc++ IDE
*/
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int N,temp;
int *A;
int i,j;
cout<<"Enter the number of elements in array:\n";
cin>>N;
A=new int[N];
cout<<"Enter the array\n";
for(i=0;i<N;i++)
  cin>>A[i];
for(i=1;i<N;i++)
  {temp = A[i];
  j=i-1;
  while((j>=0) && (A[j]>temp))
   {
   A[j+1]=A[j];j=j-1;
   }
  A[j+1]=temp;
  }
cout<<"\nThe Sorted array after INSERTION SORT:"<<"\n";
for(i=0;i<N;i++)
  cout<<"\t"<<A[i];
//for more codes visit Code Library
getch();
return 0;
}