From 55ea5afd8d4c8b48df1a6b0e6d1a16b7f8fd3b06 Mon Sep 17 00:00:00 2001 From: satcasm Date: Thu, 14 Jan 2021 13:06:56 +0530 Subject: [PATCH] added insertion sort in c++ --- SORTING/C++/insertionSort.cpp | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 SORTING/C++/insertionSort.cpp diff --git a/SORTING/C++/insertionSort.cpp b/SORTING/C++/insertionSort.cpp new file mode 100644 index 00000000..f32b8944 --- /dev/null +++ b/SORTING/C++/insertionSort.cpp @@ -0,0 +1,34 @@ +#include +using namespace std; + +void insertionSort(int arr[], int n) +{ + int temp,j; + for (int i = 1; i < n; i++) + { + temp = arr[i]; + j = i - 1; + while (j >= 0 && arr[j] > temp) + { // Moving the elements of array that are greater than temp, to one position ahead of their current position + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = temp; + } +} + +int main() +{ + int n; + cout << "Enter the length of array:\n"; + cin >> n; + int arr[n]; + cout << "Enter the elements of array:\n"; + for (int i = 0; i < n; i++) + cin >> arr[i]; // Taking input + insertionSort(arr, n); //Calling of insertionSort function + cout << "Sorted array elements:\n"; + for (int i = 0; i < n; i++) + cout << arr[i] << " "; //Printing out elements + return 0; +}