We can implement a simple, non-recursive bubble-sort given a stack and a temporary buffer:
- Iteratively pop two elements from the stack, swap these two elements if the first one is bigger, then push them back on a buffer.
- Repeat step 1. but reverse the direction, so all elements from the buffer will end up back on the stack.
Repeat step 1. and 2. until no more elements need to be swapped.
function bubble(stack, buffer, up = true) {
let swaps = 0;
let last = stack.pop();
while (stack.length > 0) {
let next = stack.pop();
if (up ? last > next : last < next) swaps++;
else [next, last] = [last, next];
buffer.push(next);
}
buffer.push(last);
return swaps;
}
function sort(stack, up = true, buffer = []) {
do bubble(stack, buffer, !up);
while (bubble(buffer, stack, up) > 0);
return stack;
}
// Example:
console.log(sort([6,3,9,3,2,8])); // [2, 3, 3, 6, 8, 9]
For a recursive solution, see https://stackoverflow.com/a/41293937/1647737