Created
October 11, 2019 22:12
-
-
Save MikeLuDev/d125b8a50556fee88a7ae5260514d64f to your computer and use it in GitHub Desktop.
CTCI 3.5
This file contains hidden or 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
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