From 7d0dc281318d66ca351d7755b8e712d0257b2e4e Mon Sep 17 00:00:00 2001 From: meabhi <46453858+AbhimanyuSaini@users.noreply.github.com> Date: Wed, 14 Oct 2020 22:39:39 +0530 Subject: [PATCH] inserion_sort This is the file for insertion sort. --- algorithms/insertion_sort | 45 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 algorithms/insertion_sort diff --git a/algorithms/insertion_sort b/algorithms/insertion_sort new file mode 100644 index 0000000..901936a --- /dev/null +++ b/algorithms/insertion_sort @@ -0,0 +1,45 @@ +#include +using namespace std; +#include +using namespace std; + +void insertionSort(int arr[], int n) { + for(int i = 1; i < n; i++) { + int current = arr[i]; + int j; + for(j = i - 1; j >= 0; j--) { + if(current < arr[j]) { + arr[j+1] = arr[j]; + } + else { + break; + } + } + arr[j+1] = current; + } + +} + +void printArray(int input[], int n) { + for(int i = 0; i < n; i++) { + cout << input[i] << " " ; + } + cout << endl; +} + +int main() { + // Take array input from the user + int n; + cin >> n; + + int input[100]; + + for(int i = 0; i < n; i++) { + cin >> input[i]; + } + + insertionSort(input, n); + + printArray(input, n); + +}