Sorting a Stack Data Structures in C++
How Sorting a Stack Data Structure works in C++?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
#include <stdlib.h> #include <iostream> using namespace std; //member functions declaration void insertionSort(int arr[], int length); void printArray(int array[], int size); // main function int main() { int array[6] = {1, 6, 9, 2, 7, 3}; // calling insertion sort function to sort the array insertionSort(array, 6); return 0; } void insertionSort(int arr[], int length) { int i, j, key; for (i = 0; i < length; i++) { j = i; while (j >
0 && arr[j - 1] > arr[j]) { key = arr[j]; arr[j] = arr[j - 1]; arr[j - 1] = key; j--; } } cout << "Sorted Array: "; // print the sorted array printArray(arr, length); } // function to print the given array void printArray(int array[], int size) { int j; for (j = 0; j < size; j++) { cout <<" "<< array[j]; } cout << endl; } |
Output
Sorted Array: 1, 2, 3, 6, 7