Created
July 3, 2014 01:10
-
-
Save chrislukkk/8094d2bafe238cc966c1 to your computer and use it in GitHub Desktop.
CareerCup_3.6 - SortingStack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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