diff --git a/C++/InsertionSort.cpp b/C++/InsertionSort.cpp index 7612ccc..a561b5d 100644 --- a/C++/InsertionSort.cpp +++ b/C++/InsertionSort.cpp @@ -1,50 +1,35 @@ - -// C++ program for insertion sort - -#include +#include using namespace std; - -// Function to sort an array using -// insertion sort -void insertionSort(int arr[], int n) -{ - int i, key, j; - for (i = 1; i < n; i++) - { - key = arr[i]; - j = i - 1; - - // Move elements of arr[0..i-1], - // that are greater than key, to one - // position ahead of their - // current position - while (j >= 0 && arr[j] > key) - { - arr[j + 1] = arr[j]; - j = j - 1; - } - arr[j + 1] = key; - } +void display(int *array, int size) { + for(int i = 0; i 0 && array[j-1]>key) { + array[j] = array[j-1]; + j--; + } + array[j] = key; //insert in right place + } } - -// Driver code -int main() -{ - int arr[] = { 12, 11, 13, 5, 6 }; - int N = sizeof(arr) / sizeof(arr[0]); - - insertionSort(arr, N); - printArray(arr, N); - - return 0; +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 elements:" << endl; + for(int i = 0; i> arr[i]; + } + cout << "Array before Sorting: "; + display(arr, n); + insertionSort(arr, n); + cout << "Array after Sorting: "; + display(arr, n); } +