Skip to content

Instantly share code, notes, and snippets.

@arastu
Last active October 13, 2017 00:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arastu/ad1e46d464e2c6eb1eabb286cbf25a8f to your computer and use it in GitHub Desktop.
Save arastu/ad1e46d464e2c6eb1eabb286cbf25a8f to your computer and use it in GitHub Desktop.
Sorting Integers with two stacks in javascript
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