From f59d27f2e2528793773c7a8249983da0eecbc3db Mon Sep 17 00:00:00 2001 From: Umang Agarwal <46571828+umangagarwal11@users.noreply.github.com> Date: Wed, 2 Oct 2019 00:23:39 +0530 Subject: [PATCH] Insertion sort while acceptiing the numbers itself --- Sorting/Insertion_sort_2.cpp | 52 ++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Sorting/Insertion_sort_2.cpp diff --git a/Sorting/Insertion_sort_2.cpp b/Sorting/Insertion_sort_2.cpp new file mode 100644 index 00000000000..2a94f9b25c6 --- /dev/null +++ b/Sorting/Insertion_sort_2.cpp @@ -0,0 +1,52 @@ +//To sort the array while accepting values itself +#include +using namespace std; + +int main() +{ + int n; + cout << "\nEnter the length of your array : "; + cin >> n; + int Array[n]; + cout << "\nEnter any " << n << " Numbers for Unsorted Array : "; + + //Input + for (int i = 0; i < n; i++) + { + int temp; + cin>>temp; + //accepted new value + int j = i - 1; + //checking if the last element in the array is greater than the accepted number + //if yes, keep moving the numbers one step to the right + while (j >= 0 && temp < Array[j]) + { + Array[j + 1] = Array[j]; + j--; + } + //add the accepted number to the desired location + Array[j + 1] = temp; + } + + //Output + cout << "\nSorted Array : "; + for (int i = 0; i < n; i++) + { + cout << Array[i] << "\t"; + } + return 0; +} + +/* +Test case: +Enter the length of your array : 5 + +Enter any 5 Numbers for Unsorted Array : 1 +2 +6 +3 +0 + +Sorted Array : 0 1 2 3 6 + +*/