From 27262e8406df4c3496b6bf43a11756ba0789218b Mon Sep 17 00:00:00 2001 From: Saurabh <54810143+kestsaurav21@users.noreply.github.com> Date: Sun, 4 Oct 2020 01:32:25 +0530 Subject: [PATCH] Create Insertion Sort --- .../cpp/algorithms/sorting/InsertionSort.cpp | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/main/cpp/algorithms/sorting/InsertionSort.cpp diff --git a/src/main/cpp/algorithms/sorting/InsertionSort.cpp b/src/main/cpp/algorithms/sorting/InsertionSort.cpp new file mode 100644 index 0000000..ae3cefe --- /dev/null +++ b/src/main/cpp/algorithms/sorting/InsertionSort.cpp @@ -0,0 +1,41 @@ +#include +using namespace std; + +//Function to print array. +void display(int arr[], int size) +{ + int i; + for (i=0; i < size; i++) + cout<< arr[i]<<"\t"; + cout<<"\n"; +} + +//Main function to run the program. +int main() +{ + int array[] = {5, 3, 1, 9, 8, 2, 4,7}; + int size = sizeof(array)/sizeof(array[0]); + + cout<<"Before Insertion sort: \n"; + display(array, size);//Using dispaly function to print unsorted array. + + int i, target, j; + for (i = 1; i < size; i++) + { + target = array[i]; + j = i - 1; + + /* Here the elements in b/w arrary[0 to i-1] + which are greater than target are moved + ahead by 1 position each*/ + while (j >= 0 && array[j] > target) + { + array[j + 1] = array[j]; + j = j - 1; + } + array[j + 1] = target; + } + cout<<"After Insertion sort: \n"; + display(array, size);//Using dispaly function to print sorted array. + return 0; +}