Skip to content

Instantly share code, notes, and snippets.

@luthfianto
Last active February 25, 2019 16:50
Show Gist options
  • Save luthfianto/8719e558b6298b7efaea975fbe6b3a89 to your computer and use it in GitHub Desktop.
Save luthfianto/8719e558b6298b7efaea975fbe6b3a89 to your computer and use it in GitHub Desktop.
/**
*
* @param {unknown[]} arr
* @return {unknown[]}
*/
function mergeSort(arr) {
if (arr.length === 1) {
return arr;
}
const indexMiddle = Math.trunc(arr.length / 2);
const left = arr.slice(0, indexMiddle);
const right = arr.slice(indexMiddle);
return merge(mergeSort(left), mergeSort(right));
}
/**
*
* @param {unknown[]} left
* @param {unknown[]} right
*/
function merge(left, right) {
let result = [];
let indexLeft = 0;
let indexRight = 0;
while (indexLeft < left.length && indexRight < right.length) {
const lefty = left[indexLeft];
const righty = right[indexRight];
if (lefty < righty) {
result.push(lefty);
indexLeft++;
} else {
result.push(righty);
indexRight++;
}
}
const unpushedLeft = left.slice(indexLeft);
const unpushedRight = right.slice(indexRight);
console.debug({ result }, { indexLeft, unpushedLeft }, { indexRight, unpushedRight })
return [...result, ...unpushedLeft, ...unpushedRight];
}
const list = [2, 5, 1, 3, 7, 2, 3, 8, 6, 3]
console.log(mergeSort(list)) // [ 1, 2, 2, 3, 3, 3, 5, 6, 7, 8 ]
/**
*
* @param {unknown[]} arr
* @return {unknown[]}
*/
function quickSort(arr) {
if (arr.length < 2) {
return arr;
}
const pivot = arr[0];
const left = [];
const right = [];
const listLength = arr.length;
for (let i = 1; i < listLength; i++) {
const value = arr[i];
if (value < pivot) {
left.push(value);
} else {
right.push(value);
}
}
return [...quickSort(left), pivot, ...quickSort(right)];
};
const list = [2, 5, 1, 3, 7, 2, 3, 8, 6, 3]
console.log(quickSort(list)) // [ 1, 2, 2, 3, 3, 3, 5, 6, 7, 8 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment