Last active
March 19, 2019 13:17
-
-
Save marsgpl/92c209d7d14b90161766aa5cae09add0 to your computer and use it in GitHub Desktop.
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
const Stack = function(data = []) { | |
this.data = data | |
} | |
Stack.prototype.push = function(value) { | |
this.data.push(value) | |
} | |
Stack.prototype.pop = function() { | |
return this.data.pop() | |
} | |
Stack.prototype.top = function() { | |
return this.data[this.data.length-1] | |
} | |
Stack.prototype.empty = function() { | |
return this.data.length == 0 | |
} | |
Stack.prototype.sort = function() { | |
const sorted = new Stack | |
while ( !this.empty() ) { | |
sorted.orderedInsert(this.pop()) | |
} | |
this.data = sorted.data | |
} | |
Stack.prototype.orderedInsert = function(value) { | |
if ( this.empty() || this.top() <= value ) { | |
this.push(value) | |
} else { | |
let v = this.pop() | |
this.orderedInsert(value) | |
this.push(v) | |
} | |
} | |
const sampleData = Array.from(new Array(100)).map((v,i)=>i+1).sort(()=>Math.random()-.5) | |
const sampleStack = new Stack(sampleData) | |
console.log(sampleStack.data) | |
sampleStack.sort() | |
console.log(sampleStack.data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment