If you are a c# beginner or want to start learning the c# programming language, then this program will help you to understand the basics of c# programming. In this program, we are going to share C# program to sort an array using the stack with the output.
Copy the below c# program and execute it in your Microsoft Visual Studio IDE (Integrated Development Environment). At the end of this program, I have shared the output program.
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 53 54 55 56 57 |
using System; using System.Collections.Generic; class arraySortingProgram { //This function return the sorted stack static Stack<int> sortStack(Stack<int> input) { Stack<int> tmpStack = new Stack<int>(); while (input.Count != 0) { int tmp = input.Peek(); input.Pop(); while (tmpStack.Count != 0 && tmpStack.Peek() < tmp) { input.Push(tmpStack.Peek()); tmpStack.Pop(); } tmpStack.Push(tmp); } return tmpStack; } static void sortArrayUsingStacks(int []arr, int n) { Stack<int> input = new Stack<int>(); 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.Peek(); tmpStack.Pop(); } } static void Main() { int []arr = new int[] {10, 5, 15, 45}; int n = arr.Length; sortArrayUsingStacks(arr, n); for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); } } |
Input : 7 4 10 20 2 5 9 1
Output : 1 2 4 5 7 9 10 20
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.