Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void sortStack(Stack *A) {
- Stack temp = initStack();
- char curr;
- while (!isEmpty(*A)) {
- // Remove the top element from the original stack
- curr = topElem(*A);
- Pop(A);
- // Transfer elements from temp back to the original stack if they are larger than the current element
- while (!isEmpty(temp) && topElem(temp) > curr) {
- Push(A, topElem(temp));
- Pop(&temp);
- }
- // Push the current element into the temp stack
- Push(&temp, curr);
- }
- // Transfer sorted elements back to the original stack
- while (!isEmpty(temp)) {
- Push(A, topElem(temp));
- Pop(&temp);
- }
- }
- // Insert Sorted:
- void insertSorted(Stack *A, char elem) {
- Stack temp = initStack();
- // Transfer elements from original stack to temp until we find the correct position for elem
- while (!isEmpty(*A) && topElem(*A) > elem) {
- Push(&temp, topElem(*A));
- Pop(A);
- }
- // Insert the new element at the correct position
- Push(A, elem);
- // Move the rest of the elements back from temp to the original stack
- while (!isEmpty(temp)) {
- Push(A, topElem(temp));
- Pop(&temp);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement