I am trying to figure out an optimal solution for the following problem:
Given a stack of
20integers, sort the stack so that only values in range from1to4would remain in ascending order. You may only move one value at a time.
I have implemented an iterative & a recursive quick sort & now I'm looking for more optimal solutions. I have come up with the following so far, which runs on average approx 10x faster over 10k iterations. I am struggling to reason about space & time complexity & I'm sure there's plenty of room for a better solution.
Which sorts should I be considering? Which data types should I be considering? What's the best possible worse case time complexity O(?) for the given problem?
Stack<Integer> stack = new Stack<>();
stack.push(5);
stack.push(3);
stack.push(2);
stack.push(1);
stack.push(3);
stack.push(5);
stack.push(3);
stack.push(1);
stack.push(4);
stack.push(7);
HashMap<Integer, Integer> map = new HashMap<>();
map.put(1, 0);
map.put(2, 0);
map.put(3, 0);
map.put(4, 0);
int popped;
while (!stack.isEmpty()) {
popped = stack.pop();
if (map.containsKey(popped)) {
map.put(popped, map.get(popped) + 1);
}
}
while (map.get(4) > 0) {
stack.push(4);
map.put(4, map.get(4) - 1);
}
while (map.get(3) > 0) {
stack.push(3);
map.put(3, map.get(3) - 1);
}
while (map.get(2) > 0) {
stack.push(2);
map.put(2, map.get(2) - 1);
}
while (map.get(1) > 0) {
stack.push(1);
map.put(1, map.get(1) - 1);
}
move one valueleaves too much room for interpretation: Move arbitrarily within stack? Move to a second stack? Just push & pop "the" (one&only) stack?