forked from jmcilhargey/cracking-the-coding-interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchpt3-sort-stack.js
More file actions
49 lines (38 loc) · 1.22 KB
/
chpt3-sort-stack.js
File metadata and controls
49 lines (38 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
function Stack() {
this.values = [];
}
Stack.prototype.push = function(value) {
this.values.push(value);
};
Stack.prototype.pop = function() {
return this.values.pop();
};
Stack.prototype.peek = function() {
return this.values[this.values.length - 1];
};
Stack.prototype.isEmpty = function() {
return this.values.length === 0;
};
// We want to sort a stack so that the smallest values are on the top using only 1 additional stack
var exampleStack = new Stack();
exampleStack.push(1);
exampleStack.push(6);
exampleStack.push(2);
exampleStack.push(5);
exampleStack.push(9);
function sortUnsortedStack(unsortedStack) {
var orderedStack = new Stack();
// Keep going while there are still values in our unsorted stack
while (unsortedStack.values.length > 0) {
// Store the top unsorted value in a variable
var nextValue = unsortedStack.pop();
// As long as there are values in the ordered stack that are bigger than our popped value
while (!orderedStack.isEmpty() && nextValue < orderedStack.peek()) {
unsortedStack.push(orderedStack.pop());
}
orderedStack.push(nextValue);
}
return orderedStack;
}
var ourSortedStack = sortUnsortedStack(exampleStack);
console.log(ourSortedStack.values);