Created
January 19, 2022 10:28
-
-
Save simone-sanfratello/045ad9363695e616c3fe2a781a158591 to your computer and use it in GitHub Desktop.
quicksort matrix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const t = require('tap') | |
const cases = [ | |
{ | |
matrix: [3, 5, 1, 3, 6, 2], | |
cols: 1, | |
result: [1, 2, 3, 3, 5, 6] | |
}, | |
{ | |
matrix: [3, 5, 1, 3, 6, 2], | |
cols: 2, | |
result: [1, 3, 3, 5, 6, 2] | |
} | |
] | |
function partition (arr, cols, startIndex, endIndex) { | |
let index = startIndex | |
let aux | |
for (let i = index; i < endIndex; i += cols) { | |
let swap | |
// comparing logic | |
for (let j = 0; j < cols; j++) { | |
if (arr[i + j] < arr[endIndex + j]) { | |
swap = true | |
break | |
} | |
} | |
if (!swap) { | |
continue | |
} | |
// swap rows | |
for (let j = 0; j < cols && i != index; j++) { | |
aux = arr[i + j] | |
arr[i + j] = arr[index + j] | |
arr[index + j] = aux | |
} | |
index += cols | |
} | |
// swap pivot row | |
for (let j = 0; j < cols; j++) { | |
aux = arr[endIndex + j] | |
arr[endIndex + j] = arr[index + j] | |
arr[index + j] = aux | |
} | |
return index | |
} | |
function quickSort (arr, cols = 1, startIndex = 0, endIndex = arr.length - cols) { | |
if (startIndex >= endIndex) { | |
return | |
} | |
const pivotIndex = partition(arr, cols, startIndex, endIndex) | |
quickSort(arr, cols, startIndex, pivotIndex - cols) | |
quickSort(arr, cols, pivotIndex + cols, endIndex) | |
return arr | |
} | |
for (let i = 0; i < cases.length; i++) { | |
t.test(`#${i + 1}`, async (t) => { | |
const a = [...cases[i].matrix] | |
t.same(quickSort(a, cases[i].cols), cases[i].result) | |
console.log({ cols: cases[i].cols }) | |
console.log(cases[i].matrix) | |
console.log(a) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment