Skip to content

Commit fbb0bb6

Browse files
committed
Add Quick Sort Test
1 parent 3fd9836 commit fbb0bb6

File tree

2 files changed

+62
-1
lines changed

2 files changed

+62
-1
lines changed

src/sort/quickSort.test.ts

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import quickSort from "./quickSort";
2+
3+
describe("Test for Quick Sort", () => {
4+
const nTimes = 100;
5+
const SIZE = 100;
6+
7+
test("testing if QS sort random array using random pivot", () => {
8+
for (let i = 0; i < nTimes; i++) {
9+
const arr = Array.from({ length: SIZE }, () =>
10+
Math.floor(Math.random() * 1000)
11+
);
12+
const sortedArr = quickSort(arr);
13+
const jsSortedArr = arr.slice().sort((a, b) => a - b);
14+
expect(sortedArr[0]).toEqual(jsSortedArr);
15+
}
16+
});
17+
18+
test("testing if QS sort random array using first element as pivot", () => {
19+
for (let i = 0; i < nTimes; i++) {
20+
const arr = Array.from({ length: SIZE }, () =>
21+
Math.floor(Math.random() * 1000)
22+
);
23+
const sortedArr = quickSort(arr, 0, arr.length, 0);
24+
const jsSortedArr = arr.slice().sort((a, b) => a - b);
25+
expect(sortedArr[0]).toEqual(jsSortedArr);
26+
}
27+
});
28+
29+
test("testing if QS sort random array using last element as pivot", () => {
30+
for (let i = 0; i < nTimes; i++) {
31+
const arr = Array.from({ length: SIZE }, () =>
32+
Math.floor(Math.random() * 1000)
33+
);
34+
const sortedArr = quickSort(arr, 0, arr.length, 1);
35+
const jsSortedArr = arr.slice().sort((a, b) => a - b);
36+
expect(sortedArr[0]).toEqual(jsSortedArr);
37+
}
38+
});
39+
40+
test("testing if QS sort random array using 'median of 3' element as pivot", () => {
41+
for (let i = 0; i < nTimes; i++) {
42+
const arr = Array.from({ length: SIZE }, () =>
43+
Math.floor(Math.random() * 1000)
44+
);
45+
const sortedArr = quickSort(arr, 0, arr.length, 2);
46+
const jsSortedArr = arr.slice().sort((a, b) => a - b);
47+
expect(sortedArr[0]).toEqual(jsSortedArr);
48+
}
49+
});
50+
51+
test("testing if QS sort random array using 'median of 3 random elements' as pivot", () => {
52+
for (let i = 0; i < nTimes; i++) {
53+
const arr = Array.from({ length: SIZE }, () =>
54+
Math.floor(Math.random() * 1000)
55+
);
56+
const sortedArr = quickSort(arr, 0, arr.length, 2);
57+
const jsSortedArr = arr.slice().sort((a, b) => a - b);
58+
expect(sortedArr[0]).toEqual(jsSortedArr);
59+
}
60+
});
61+
});

src/sort/quickSort.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ const quickSort = (
122122
right = arr.length,
123123
chooseP = 3
124124
): [number[], number] => {
125-
if (right - left < 1) return [arr, 0];
125+
if (right - left <= 1) return [arr, 0];
126126
// to count the number of comparisons
127127
const comp = right - left - 1;
128128
let cl, cr;

0 commit comments

Comments
 (0)