Skip to content

Instantly share code, notes, and snippets.

@greatsharma
Last active April 29, 2019 09:47
Show Gist options
  • Save greatsharma/4bbf3193362a5c3a701722ba759dd291 to your computer and use it in GitHub Desktop.
Save greatsharma/4bbf3193362a5c3a701722ba759dd291 to your computer and use it in GitHub Desktop.
A simple c++ program to sort an array using insertion sort algorithm.
/*
Name: Insertion Sort
Author: Gaurav Sharma
Date: 26-04-19 17:31
Description: A simple c++ program to sort an array using insertion sort algorithm.
*/
#include <iostream>
#include <conio.h>
#include <time.h>
#define NO_RUNS 100
using namespace std;
int insertionSort(int *arr, int size)
{
int no_comp = 0;
for (int i = 1; i < size; i++)
{
int temp = arr[i];
for (int j = i - 1; j >= 0; j--)
{
++no_comp;
if (temp < arr[j])
{
arr[j + 1] = arr[j];
arr[j] = temp;
}
}
}
return no_comp;
}
int main()
{
srand(time(0));
int *compr_array = new int[NO_RUNS];
for (int k = 0; k < NO_RUNS; k++)
{
cout << "\n\nRUN " << k + 1;
int size = 5 + (rand() % (15 - (5) + 1));
cout << "\n\nsize : " << size;
int *arr = new int[size];
cout << "\n\nInitial array : ";
for (int i = 0; i < size; i++)
{
arr[i] = -100 + (rand() % (100 - (-100) + 1));
cout << " " << arr[i];
}
int no_comp = insertionSort(arr, size);
compr_array[k] = no_comp;
cout << "\n\ntotal no of comparisons : " << no_comp;
cout << "\n\nSorted array : \n";
for (int i = 0; i < size; i++)
{
cout << "\n"
<< arr[i];
}
}
getch();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment