Skip to content

Commit 2a8b4a4

Browse files
committed
test: add IntroSort tests
1 parent 08d8c6b commit 2a8b4a4

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

Sorts/test/IntroSort.test.js

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import { introsort } from '../IntroSort'
2+
3+
describe('introsort', () => {
4+
it('should have a robust default comparator', () => {
5+
// toString, null, undefined
6+
const mixedData = [undefined, '2', 1, false, null]
7+
introsort(mixedData)
8+
expect(mixedData).toEqual([1, '2', false, null, undefined])
9+
10+
// Symbol
11+
expect(() => introsort([Symbol(), Symbol()])).toThrowError()
12+
})
13+
14+
it('fails gracefully', () => {
15+
introsort('string')
16+
introsort([])
17+
introsort([1, 2, 3], 'string')
18+
})
19+
20+
it('should sort randomly generated data', function demo1() {
21+
// make array
22+
const data = []
23+
const size = 10_000
24+
for (let i = 0; i < size; i++) {
25+
const temp = Math.random() * Number.MAX_SAFE_INTEGER
26+
data.push(temp)
27+
}
28+
29+
// custom comparator
30+
const c = function (a, b) {
31+
return a - b
32+
}
33+
introsort(data, c)
34+
35+
// check that all numbers are smaller than the one after them
36+
let faulty = false
37+
for (let i = 1; i < size; i++) {
38+
if (data[i - 1] > data[i]) {
39+
faulty = true
40+
break
41+
}
42+
}
43+
44+
expect(faulty).toEqual(false)
45+
})
46+
47+
it('should match the sorting of Array.sort()', function demo2() {
48+
// make arrays
49+
const data = []
50+
const data2 = []
51+
const size = 10_000
52+
for (let i = 0; i < size; i++) {
53+
const temp = Math.random() * Number.MAX_SAFE_INTEGER
54+
data.push(temp)
55+
data2.push(temp)
56+
}
57+
58+
// sort
59+
introsort(data)
60+
data2.sort()
61+
62+
// verify
63+
let faulty = false
64+
for (let i = 0; i < size; i++) {
65+
if (data[i] !== data2[i]) {
66+
faulty = true
67+
break
68+
}
69+
}
70+
71+
expect(faulty).toEqual(false)
72+
})
73+
})

0 commit comments

Comments
 (0)