Skip to content

Instantly share code, notes, and snippets.

@chrislukkk
Created July 3, 2014 01:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrislukkk/8094d2bafe238cc966c1 to your computer and use it in GitHub Desktop.
Save chrislukkk/8094d2bafe238cc966c1 to your computer and use it in GitHub Desktop.
CareerCup_3.6 - SortingStack
package Chapter3;
import java.util.Random;
public class StackSorting {
public static void sort(Stack<Integer> stack) {
Stack<Integer> tempStack = new Stack<>();
while (!stack.isEmpty()) {
int v = stack.pop();
int moveCount = 0;
// move all elements in temp stack which is smaller than
// the value (from temp to original stack)
while ((!tempStack.isEmpty()) && v > tempStack.peek()) {
stack.push(tempStack.pop());
moveCount++;
}
// push the new value
tempStack.push(v);
// push bakc the poped elements
while (moveCount > 0) {
tempStack.push(stack.pop());
moveCount--;
}
}
while (!tempStack.isEmpty()) {
stack.push(tempStack.pop());
}
}
public static void main(String[] args) {
Random d = new Random();
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < 10; i++) {
stack.push(d.nextInt(10000));
}
System.out.print("Before sorting: ");
stack.print();
sort(stack);
System.out.print("After sorting: ");
stack.print();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment