/***************************************************************
* Name: Rafael Orta
* Course: Computer Science & Programming
* Class: PDS-04225
* Date: 04/10/22
* File Name: InsertionSort.cpp
*****************************************************************
* Purpose: Demonstrate the implementation of the insertion sort algorithm
* using C++
*****************************************************************/
#include<iostream>
using namespace std;
void display(int*, int);
void insertionSort(int*, int);
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n]; //create an array with given number of elements
cout << "Enter the " << n << " elements separated by space:" << endl;
for(int i = 0; i<n; i++) {
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr, n);
insertionSort(arr, n);
cout << "Array after Sorting: ";
display(arr, n);
}
void display(int *array, int size) {
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << endl;
}
void insertionSort(int *array, int size) {
int key, j;
for(int i = 1; i<size; i++) {
key = array[i];//take value
j = i;
while(j > 0 && array[j-1]>key) {
array[j] = array[j-1];
j--;
}
array[j] = key; //insert in right place
}
}