Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
sortStack
class Stack { constructor() { this.values = []; } push(value) { this.values.push(value) } pop() { return this.values.pop(); } peek() { return this.values[this.values.length - 1]; } size() { return this.values.length; } isEmpty() { return this.values.length === 0; } } function sortStack(stack) { let temp = new Stack(); temp.push(stack.pop()); // move elements from stack to temp but sort them 1 at a time while (!stack.isEmpty()) { let curr = stack.pop(); let count = 0; // remove elements from temp to get the correct spot for curr while (!temp.isEmpty() && curr < temp.peek()) { stack.push(temp.pop()); count++; } temp.push(curr); // after pushing curr onto the sorted stack, pop all the other elements back for (let i = 0; i < count; ++i) { temp.push(stack.pop()); } } // temp is min to largest we want to pop onto stack to have min @ the top while (!temp.isEmpty()) { stack.push(temp.pop()); } return stack; } let stack = new Stack(); stack.push(1) stack.push(5) stack.push(3) stack.push(4) stack.push(5) console.log(sortStack(stack))
run
|
edit
|
history
|
help
0
adfafaf
Animal categories
House prices
js object to json string
Triangle
Functions
greeting
Prime Number
Alternating Sign Fibonacci
challenge