|
const { getMiddleElement, getPartitions, mergeAndSort, quickSort } = require('./index'); |
|
const { isEqual, printConsole } = require('./test_utils'); |
|
|
|
(() => { |
|
console.log("\nGet middle element"); |
|
// Examples. The first element is the length of the array, the second is the middle index |
|
const tt = [[5, 2], [4, 1], [1, 0], [0, 0], [2, 0], [3, 1]]; |
|
for (t of tt) { |
|
const r = getMiddleElement(t[0]); |
|
if (r !== t[1]) { |
|
throw `For ${t[0]} => Got ${r}, expected ${t[1]}`; |
|
} |
|
printConsole(".", "green"); |
|
} |
|
})(); |
|
|
|
(() => { |
|
console.log("\nQuicksort"); |
|
const tt = [ |
|
[[3,1,2],[1,2,3]], |
|
[[1,2],[1,2]], |
|
[[3,1,2],[1,2,3]], |
|
[[1],[1]], |
|
[[1,3,2,4],[1,2,3,4]], |
|
[[4,3,2,1],[1,2,3,4]], |
|
[[5,4,3,2,1],[1,2,3,4,5]], |
|
[[5,0,1,2,3],[0,1,2,3,5]], |
|
[[2,0,4,2,5,4],[0,2,2,4,4,5]], |
|
]; |
|
for (t of tt) { |
|
const r = quickSort(t[0]); |
|
if (!isEqual(r, t[1])) { |
|
throw `For ${t[0]} => Got ${r}, expected ${t[1]}`; |
|
} |
|
printConsole(".", "green"); |
|
} |
|
})(); |
|
|
|
(() => { |
|
console.log("\nGet partitions"); |
|
// Examples. The first element is the length of the array, the second is the middle index |
|
const tt = [ |
|
[ |
|
[5,4,3,2,1], |
|
[3, [2,1], [5,4]] |
|
], |
|
[ |
|
[3,1,5,4], |
|
[1, [], [3,5,4]] |
|
], |
|
[ |
|
[1], |
|
[1, [], []] |
|
], |
|
]; |
|
for (t of tt) { |
|
const r = getPartitions(t[0]); |
|
if (r[0] !== t[1][0]) { |
|
throw "Pivot element is wrong"; |
|
} |
|
if (!isEqual(r[1], t[1][1])) { |
|
throw "Lower array is wrong" |
|
} |
|
if (!isEqual(r[2], t[1][2])) { |
|
throw "Higher array is wrong" |
|
} |
|
printConsole(".", "green"); |
|
} |
|
})(); |
|
|
|
(() => { |
|
console.log("\nMerge and sort"); |
|
// Examples. The first element is the length of the array, the second is the middle index |
|
const tt = [ |
|
[ |
|
[3,1,4], [5,2], |
|
[1,2,3,4,5] |
|
], |
|
[ |
|
[3,1,4,2], [1,5,2], |
|
[1,2,3,4,5] |
|
], |
|
[ |
|
[1,1], [1,1,1], |
|
[1] |
|
], |
|
[ |
|
[4,2,9,1,2], [], |
|
[1,2,4,9] |
|
], |
|
]; |
|
for (t of tt) { |
|
const r = mergeAndSort(t[0], t[1]); |
|
if (!isEqual(r, t[2])) { |
|
throw `Result is wrong: ${r}`; |
|
} |
|
printConsole(".", "green"); |
|
} |
|
})(); |