Stack Hack 2 Post
Stack hack 2 blog post for AP CSA
import java.util.Stack;
public class StackSorter {
public void sort() {
Stack<Integer> stack = new Stack<Integer>();
ArrayList<Integer> usedNumbers = new ArrayList<Integer>();
stack.push(3);
stack.push(7);
stack.push(5);
stack.push(1);
stack.push(2);
stack.push(10);
stack.push(7);
System.out.println("Stack before sort: " + stack.toString());
int[] tempValues = new int[stack.size()];
int index = 0;
while (!stack.isEmpty()) {
tempValues[index] = stack.pop();
index++;
}
int swapCount = 0;
for (int i = 0; i < tempValues.length - 1; i++) {
if (tempValues[i] > tempValues[i + 1]) {
int temp = tempValues[i + 1];
tempValues[i + 1] = tempValues[i];
tempValues[i] = temp;
swapCount++;
}
if (i == tempValues.length - 2 && swapCount != 0) {
swapCount = 0;
i = -1;
}
}
for (int item : tempValues) {
stack.push(item);
}
System.out.println("Stack after sort: " + stack.toString());
}
public static void main(String[] args) {
StackSorter myObj = new StackSorter();
myObj.sort();
}
}
StackSorter.main(null);