Skip to content

Commit 42eec8c

Browse files
committed
Added solution to ch3-5 and associated tests.
1 parent 1381ee7 commit 42eec8c

File tree

2 files changed

+88
-0
lines changed

2 files changed

+88
-0
lines changed

src/chapter3/ch3-q5.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
'use strict';
2+
3+
function peek(stack) {
4+
return stack[stack.length - 1];
5+
}
6+
7+
function isEmpty(stack) {
8+
return stack.length === 0;
9+
}
10+
11+
/**
12+
* Sort the stack by taking one item off the input stack at a time, find the
13+
* right place within the processed items in the temp stack to insert it into.
14+
* Insertion is done by holding the next value aside and moving the temp stack
15+
* values into the input stack until the right spot is found.
16+
*
17+
* N = |stack|
18+
* Time: O(N^2)
19+
* Additional space: O(1) - while there are 2 stacks there are only a fixed
20+
* number of items.
21+
*/
22+
export function sortStack(stack) {
23+
let temp = [];
24+
temp.push(stack.pop());
25+
while (!isEmpty(stack)) {
26+
let curr = stack.pop(),
27+
count = 0;
28+
29+
while (!isEmpty(temp) && curr < peek(temp)) {
30+
stack.push(temp.pop());
31+
++count;
32+
}
33+
temp.push(curr);
34+
for (let i = 0; i < count; ++i) {
35+
temp.push(stack.pop());
36+
}
37+
}
38+
39+
while (!isEmpty(temp)) {
40+
stack.push(temp.pop());
41+
}
42+
43+
return stack;
44+
}

src/chapter3/ch3-q5.spec.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import { expect } from 'chai';
2+
import * as funcs from './ch3-q5';
3+
4+
for (let key in funcs) {
5+
let func = funcs[key];
6+
7+
describe('ch3-q5: ' + key, function() {
8+
9+
it('does not crash on an empty list', function() {
10+
let stack = [];
11+
expect(() => func(stack)).to.not.throw(Error).and.to.equal(stack);
12+
});
13+
14+
it('works with a single element stack', function() {
15+
expect(func([4])).to.eql([4]);
16+
});
17+
18+
[
19+
[5, 3, 1, 4, 6, 2],
20+
[9, 8, 7, 6, 5, 4, 3, 2, 1],
21+
[1, 2, 1, 2, 1, 2, 1, 2],
22+
[1, 2, 3, 4, 5, 6, 7, 8, 9],
23+
[100, 15, 20, 30, 10, 80, 50, 45, 75, 35, 85, 55, 40, 99]
24+
].forEach(arg => {
25+
26+
it(`correctly sorts ${arg}`, function() {
27+
let expected = arg.slice(0).sort((a, b) => a < b ? 1 : a > b ? -1 : 0);
28+
29+
expect(func(arg)).to.eql(expected);
30+
});
31+
32+
});
33+
34+
it('correctly sorts with 100 random numbers', function() {
35+
let stack = [];
36+
for (let i = 0; i < 100; ++i) {
37+
stack.push(Math.trunc(Math.random() * 9999999));
38+
}
39+
let expected = stack.slice(0).sort((a, b) => a < b ? 1 : a > b ? -1 : 0);
40+
expect(func(stack)).to.eql(expected);
41+
});
42+
43+
});
44+
}

0 commit comments

Comments
 (0)