I need help sorting a stack in DESCENDING ORDER so [44,32,21,11,0,-4,-5,-12,-24].

C++ Programming: From Problem Analysis to Program Design
8th Edition
ISBN:9781337102087
Author:D. S. Malik
Publisher:D. S. Malik
Chapter18: Stacks And Queues
Section: Chapter Questions
Problem 1TF
icon
Related questions
Question

I need help sorting a stack in DESCENDING ORDER so [44,32,21,11,0,-4,-5,-12,-24].

----------------------------------------------------------------------------------------- 

Below is my failing code for [1,-1] where [-1,1] is being returned. 

------------------------------------------------------------------------------------------

public Stack<Integer> solution(Stack<Integer> stack) {
if (!stack.isEmpty()) {
int top = stack.pop();
sort(stack);
sortUtil(stack, top);
}
return stack;
}

private static void sortUtil(Stack<Integer> stack, int data) {
if (stack.isEmpty() || stack.peek() < data) {
stack.push(data);
} else {
int top = stack.pop();
sortUtil(stack, data);
stack.push(top);
}
}

Expert Solution
trending now

Trending now

This is a popular solution!

steps

Step by step

Solved in 2 steps

Blurred answer
Knowledge Booster
Stack
Learn more about
Need a deep-dive on the concept behind this application? Look no further. Learn more about this topic, computer-science and related others by exploring similar questions and additional content below.
Similar questions
  • SEE MORE QUESTIONS
Recommended textbooks for you
C++ Programming: From Problem Analysis to Program…
C++ Programming: From Problem Analysis to Program…
Computer Science
ISBN:
9781337102087
Author:
D. S. Malik
Publisher:
Cengage Learning