MCPcopy Index your code
hub / github.com/careercup/CtCI-6th-Edition-JavaScript / sortStack

Function sortStack

chapter03/3.5 - Sort Stack/sortStack.js:8–60  ·  view source on GitHub ↗
(stack)

Source from the content-addressed store, hash-verified

6var Stack = require('./../util/Stack');
7
8var sortStack = function(stack) {
9 var tempStack = new Stack();
10 var currMin = Infinity;
11 var stackDepth = 0;
12
13 while (!stack.isEmpty()) {
14 if (stack.peek() <= currMin) {
15 if (currMin !== Infinity) {
16 tempStack.push(currMin);
17 }
18 currMin = stack.pop();
19 } else {
20 tempStack.push(stack.pop());
21 }
22 stackDepth++;
23 }
24
25 while (!tempStack.isEmpty()) {
26 stack.push(tempStack.pop());
27 }
28
29 tempStack.push(currMin);
30 currMin = Infinity;
31 stackDepth--;
32
33 while (stackDepth > 0) {
34
35 while (!stack.isEmpty()) {
36 if (stack.peek() <= currMin) {
37 if (currMin !== Infinity) {
38 tempStack.push(currMin);
39 }
40 currMin = stack.pop();
41 } else {
42 tempStack.push(stack.pop());
43 }
44 }
45
46 for (var i = 0; i < stackDepth - 1; i++) {
47 stack.push(tempStack.pop());
48 }
49
50 tempStack.push(currMin);
51 currMin = Infinity;
52 stackDepth--;
53 }
54
55 while (!tempStack.isEmpty()) {
56 stack.push(tempStack.pop());
57 }
58
59 return stack;
60};
61
62/* TEST */
63var s = new Stack();

Callers 1

sortStack.jsFile · 0.85

Calls 7

pushMethod · 0.95
isEmptyMethod · 0.95
popMethod · 0.95
isEmptyMethod · 0.45
peekMethod · 0.45
popMethod · 0.45
pushMethod · 0.45

Tested by

no test coverage detected