In this program, we are going to share a C++ program to sort an array using the stack. If you are a beginner and want to start learning the C programming, then keep your close attention in this tutorial as I am going to share a program for C++ program to sort an array using the stack.
We believe you have a basic knowledge of c programming and stack in c programming language.
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 45 46 47 48 49 50 51 52 | #include <bits/stdc++.h> using namespace std; stack<int> sortStack(stack<int> input) { stack<int> tmpStack; while (!input.empty()) { int tmp = input.top(); input.pop(); while (!tmpStack.empty() && tmpStack.top() < tmp) { input.push(tmpStack.top()); tmpStack.pop(); } tmpStack.push(tmp); } return tmpStack; } void sortArrayUsingStacks(int arr[], int n) { stack<int> input; for (int i=0; i<n; i++) input.push(arr[i]); stack<int> tmpStack = sortStack(input); for (int i=0; i<n; i++) { arr[i] = tmpStack.top(); tmpStack.pop(); } } int main() { int arr[] = {10, 1, 25, 20, 5, 15, 30}; int n = sizeof(arr)/sizeof(arr[0]); sortArrayUsingStacks(arr, n); for (int i=0; i<n; i++) cout << arr[i] << " "; return 0; } |
1 5 10 15 20 25 30
Liked this program? Do Like & share with your friends.
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.