Insertion Sort in C++

Insertion sort is a comparison sort type. It works the way in which we sort playing cards. Each element is searches its place from starting and settles if the next element is larger.

The code is implemented in C++ here.

/*
 * Insertion Sort
 * 
 * */
#include<iostream>
using namespace std;
void print(int a[],int n){
	cout<<"The elements of array are "<<endl;
	for(int i=0;i<n;i++){
		cout<<a[i]<<" ";
	}
	cout<<endl;
}
void insert_sort(int a[],int n){
	int i,j,key;
	for(i=1;i<n;i++){
		key = a[i];
		j=i-1;
		while(j>=0&&a[j]>key){
			a[j+1] = a[j];
			j--;
		}
		a[j+1] = key;
	}
}
int main(){
	int a[] = {20,10,30,45,85,23,78};
	int size = sizeof(a)/sizeof(int);
	print(a,size);
	insert_sort(a,size);
	print(a,size);
	return 0;
}
output of the program. insertion sort

One Reply to “Insertion Sort in C++”

Leave a Reply

Your email address will not be published. Required fields are marked *