Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Herrytheeagle/8c81ddb4727f0b0a6675be91b00038d8 to your computer and use it in GitHub Desktop.
Save Herrytheeagle/8c81ddb4727f0b0a6675be91b00038d8 to your computer and use it in GitHub Desktop.
Insertion sorting Technique written with C++
#include <iostream>
#include <functional>
#include <cstring>
using namespace std;
/*this is a simple sorting algorithm that just follow the same
method we use in sorting our cards when playing card games*/
//function to sort an array insertion sort.
void insertionSort(int arr[],int n)
{
cout << "......INSERTION SORTING ALGORITHM......" << endl;
int i,key,j;
for(i=1;i<n;i++)
{
key = arr[i];
j=i-1;
/*move elements of arr [0...i-1], that are greater than key
to one position ahead of their current position*/
while (j>=0 && arr[j]> key)
{
arr[j+1]=arr[j];
j=j-1;
}
arr[j+1]=key;
}
}
// A utility function to print
void printArray(int arr[],int n)
{
int i;
for(i=0;i<n; i++)
{
cout<<arr[i]<< ", ";
}
}
int main()
{
// int arr[]={4,11,13,5,60};
int arr[10];
int item, counter = 0;
do {
cout << "Enter first no in the arr and press -1 to quit => ";
cin >> item;
arr[counter] = item;
counter ++;
} while(item != -1);
cout << arr << endl;
insertionSort(arr, counter);
printArray(arr, counter);
return 0;
}
@Herrytheeagle
Copy link
Author

sorting Algorithm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment