Skip to content

Instantly share code, notes, and snippets.

@MikeLuDev
Created October 11, 2019 22:12
Show Gist options
  • Save MikeLuDev/d125b8a50556fee88a7ae5260514d64f to your computer and use it in GitHub Desktop.
Save MikeLuDev/d125b8a50556fee88a7ae5260514d64f to your computer and use it in GitHub Desktop.
CTCI 3.5
function sortStack(stack, sorted = false, inOrder = true) {
if (sorted) return stack;
const stackTwo = new Stack();
let isSorted = true;
while (stack !== null) {
const top = stack.pop();
if (stack.isEmpty()) {
stackTwo.push(top);
break;
}
const next = stack.pop();
const topToStackTwo = () => {
stackTwo.push(top);
stack.push(next);
};
const nextToStackTwo = () => {
stackTwo.push(next);
stack.push(top);
};
if (inOrder) {
if (top >= next) {
topToStackTwo();
} else {
nextToStackTwo();
isSorted = false;
}
} else {
if (top >= next) {
nextToStackTwo();
isSorted = false;
} else {
topToStackTwo();
isSorted = false;
}
}
}
return sortStack(stackTwo, isSorted, !inOrder);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment