Insertion sort algorithm and source code

#include<iostream>
#include<conio.h>
using namespace std;
int main(){
//	Insertion Sort
	int arr[6]={20, 12, 6, 7, 9, 13};	
	for(int i=1; i<6; i++){
//		Take first element as sorted array
		int current= arr[i];
//		Now from the picked element we will search to backward direction or in sorted array
		int j=i-1;
//		Base condition and check next element is greater than picked element
		while(j>=0 && current < arr[j]){
//			if yes then replace that element with the adjacent element which is right side
			arr[j+1]=arr[j];
//			and go backward direction
			j--;
		}
//		if any one condition failed either j is less than 0 and next element is not greater 
//      than picked element
// Then replace last element with current element
		arr[j+1]=current;		
	}
	
	for(int i=0; i<6; i++){
		cout<< arr[i] << "\t";
	}
	
	
	getch();
	return 0;
}
© 2016 - 2022, All Rights are Reserved.