codescracker


c++

C++ Program Insertion Sort



« Previous Program Next Program »


Insertion Sort in C++

To sort an array using insertion sort technique in C++ programming, you have to ask to the user to enter the array size and array elements in random order, now start sorting the elements of the array in ascending order using insertion sort technique as shown here in the following program.

C++ Programming Code for Insertion Sort

Following C++ program ask to the user to enter array size and array element to sort the array using insertion sort technique, then display the sorted array on the screen:

/* C++ Program - Insertion Sort */
		
#include<iostream.h>
#include<conio.h>
void main()
{
	clrscr();
	int size, arr[50], i, j, temp;
	cout<<"Enter Array Size : ";
	cin>>size;
	cout<<"Enter Array Elements : ";
	for(i=0; i<size; i++)
	{
		cin>>arr[i];
	}
	cout<<"Sorting array using selection sort ... \n";
	for(i=1; i<size; i++)
	{
		temp=arr[i];
		j=i-1;
		while((temp<arr[j]) && (j>=0))
		{
			arr[j+1]=arr[j];
			j=j-1;
		}
		arr[j+1]=temp;
	}
	cout<<"Array after sorting : \n";
	for(i=0; i<size; i++)
	{
		cout<<arr[i]<<" ";
	}
	getch();
}

When the above C++ program is compile and executed, it will produce the following result:

C++ program insertion sort

Same Program in Other Language

You may like the same program in other programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test