014 write programs sort a stack in ascending order. You should not make any special assumptions (keep it up), 014 keep
Write programs sort a stack in ascending order. You should not make any special assumptions about how this stack is implemented.
Stack operations used in the program include: push | pop | isEmpty
The most easy to think of is the priority queue for this question, which is easy to implement.
In addition, we can use a stack to sort stacks in ascending order.
Priority queue:
// Implement void sortStack (std: stack <int> & vStk) {std: priority_queue <int, std: vector <int>, std :: greater <int> Queue; while (! VStk. empty () {Queue. push (vStk. top (); vStk. pop () ;}while (! Queue. empty () {vStk. push (Queue. top (); Queue. pop ();}}
Additional stack implementation:
// Append a stack to implement void sortStack _ (std: stack <int> & vStk) {std: stack <int> Tmp; while (! VStk. empty () {int Top = vStk. top (); vStk. pop (); while (! Tmp. top () & Top <Tmp. top () {vStk. push (Tmp. top (); Tmp. pop ();} Tmp. push (Top );}}
The second algorithm has an extreme test column: If the bottom-to-top data of the original stack is small to large, for example:
1 2 3 4 5 6 7
So every time Tmp pushes a different number, it will clear all the data in the stack, such as at a certain time point.
VStk: 1 2 3 4 5
Tmp: 6 7
When Tmp needs to push 5, it needs to clear 6 7 and then in push5. At this time, the data on the vStk stack is increased:
VStk: 1 2 3 4 7 6
Tmp: 5
3. Write a C program to sort and output 10 integers in ascending order.
# Include "stdio. h"
# Define N 10 // 10 Integers
Void bubble_sort (int array [], int n)
{// Sort by Bubble Method
Int I, j, flag, temp;
For (I = 0; I <n-1; I ++)
{
Flag = 1;
For (j = 0; j <n-i-1; j ++)
{
If (array [j]> array [j + 1])
{
Temp = array [j];
Array [j] = array [j + 1];
Array [j + 1] = temp;
Flag = 0;
}
}
If (1 = flag) break;
}
}
Void main ()
{
Int a [N], I;
For (I = 0; I <N; I ++) scanf ("% d", & a [I]);
Bubble_sort (a, N );
For (I = 0; I <N; I ++)
Printf ("% d", a [I]);
Printf ("\ n ");
}
Programming in C ++: design a function template and use the Bubble Method to sort 10 Data Types in ascending order.
# Include <iostream>
Using namespace std;
Template <typename T>
Void sort (T a [], int n)
{
T t;
Int I, j;
For (j = 0; j <n-1; j ++)
For (I = 0; I <n-1-j; I ++)
If (a [I]> a [I + 1])
{
T = a [I];
A [I] = a [I + 1];
A [I + 1] = t;
}
Cout <"after sorting:" <endl;
For (I = 0; I <5; I ++)
Cout <a [I] <"";
Cout <endl;
}
Int main ()
{
Long a [5] = {5984098,-5432325,4517547, 542401,87824544 };
Int B [5] = {45, 85,-62,47, 54 };
Float c [5] = {1.2, 5.4, 65.7, 45.6,-86.1 };
Sort (a, 5 );
Sort (B, 5 );
Sort (c, 5 );
Return 0;
}