Learn-dsa..in 30 days!



























CC-18 : Implement Stack sort.

Description:

: Given a stack with integer elements, sort the integers in descending order and return the same.

Test cases and expected outputs:

Input Parameters Expected outputs
Stack nodes:
9 <- 14 <- 17 <- 34 <- 21 <- 28 <-
Stack nodes:
34 <- 28 <- 21 <- 17 <- 14 <- 9 <-
Stack nodes:
9 <- 14 <- 17 <- 3 <- 21 <- 5 <- 1 <-
Stack nodes:
21 <- 17 <- 14 <- 9 <- 5 <- 3 <- 1 <-

Pseudocode:

Initialize a Deque stack named sortedStack for storing the sorted elements.
For all elements in input stack:
While sorted stack size is not zero:
If top element of sortedStack is greater than current element of input stack:
Add top element of sortedStack to input stack.
Else break out of current loop.
Add current element of input stack to sortedStack.
At end of above loop, sortedStack contains the elements in descending sort. Return sortedStack.


Code:

public Deque<Integer> sort(Deque<Integer> stack) throws Exception{
	Deque<Integer> sortedStack=new LinkedList<Integer>();
	int num;	
	while (stack.size() != 0) {
		num=(int) stack.pollFirst();		
		while (sortedStack.size() != 0) {
			if (num < (int) sortedStack.peekFirst()){
				stack.offerFirst(sortedStack.pollFirst());
			}else {
				break;
			}
		}
		sortedStack.offerFirst(num);
	}
	return sortedStack;
}

Click here to download and run code and test cases !