Last active
October 13, 2017 00:45
-
-
Save arastu/ad1e46d464e2c6eb1eabb286cbf25a8f to your computer and use it in GitHub Desktop.
Sorting Integers with two stacks in javascript
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 Stack() { | |
this.data = [] | |
} | |
Stack.prototype.pop = function () { | |
return this.data.pop() | |
} | |
Stack.prototype.push = function (item) { | |
this.data.push(item) | |
} | |
Stack.prototype.peek = function () { | |
return this.data[this.data.length - 1] | |
} | |
Stack.prototype.toString = function() { | |
return this.data.toString() | |
} | |
Stack.prototype.isEmpty = function() { | |
return this.data.length === 0 | |
} | |
var stack1 = new Stack() | |
var stack2 = new Stack() | |
var temp | |
stack1.push(12) | |
stack1.push(34) | |
stack1.push(15) | |
stack1.push(1) | |
console.log(stack1.toString()) | |
while(!stack1.isEmpty()) { | |
temp = stack1.pop() | |
while(!stack2.isEmpty() && temp < stack2.peek()) { | |
stack1.push(stack2.pop()) | |
} | |
stack2.push(temp) | |
} | |
console.log(stack2.toString()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment