Skip to content

Instantly share code, notes, and snippets.

@FrazzIe
Created February 13, 2022 22:56
Show Gist options
  • Select an option

  • Save FrazzIe/c0d8a1133c00f3000b76177d9a6df2dc to your computer and use it in GitHub Desktop.

Select an option

Save FrazzIe/c0d8a1133c00f3000b76177d9a6df2dc to your computer and use it in GitHub Desktop.
Basic JavaScript merge sort for my own understanding with a optional custom compare func
// original: https://stackabuse.com/merge-sort-in-javascript/
/**
* Default comparison
* @param {number} left
* @param {number} right
* @returns {number}
*/
function defaultCompare(left, right)
{
return left - right
}
/**
* Merge two sorted sub-arrays into a single sorted array
* @param {any[]} left
* @param {any[]} right
* @param {function} compareFn
*/
function merge(left, right, compareFn)
{
const arr = [];
// empty sub-arrays until one is completely empty
while(left.length > 0 && right.length > 0)
{
// custom comparator check
// value < 0 assumes left < right
// shift() removes first element and returns it
if (compareFn(left[0], right[0]) < 0)
{
arr[arr.length] = left.shift();
}
else
{
arr[arr.length] = right.shift();
}
}
// concat the newly merged array and any leftover elements
return [ ...arr, ...left, ...right ];
}
/**
* Sort an array using the MergeSort algorithm
*
* Splits the array up into multiple sub-arrays and puts it back together again
* @param {any[]} arr
* @param {function} [compareFn]
*/
function sort(arr, compareFn = defaultCompare)
{
// prevent arr splitting if too small
if (arr.length < 2)
{
return arr;
}
// get half the size of arr
const half = arr.length / 2;
// remove the left half from arr
// store it in a new sub-array
const left = arr.splice(0, half);
return merge(sort(left, compareFn), sort(arr, compareFn), compareFn);
}
const payload = [100, -1, 50, 22, 2000, -50, 67, 4, 9, 250];
const payload_adv = [
{ test: 1, foo: "bar", num: 100 },
{ test: 1, foo: "bar", num: -1 },
{ test: 1, foo: "bar", num: 50 },
{ test: 1, foo: "bar", num: 22 },
{ test: 1, foo: "bar", num: 2000 },
{ test: 1, foo: "bar", num: -50 },
{ test: 1, foo: "bar", num: 67 },
{ test: 1, foo: "bar", num: 4 },
{ test: 1, foo: "bar", num: 9 },
{ test: 1, foo: "bar", num: 250 },
]
console.log("BEFORE: ", payload);
const sorted = sort(payload);
console.log("AFTER: ", sorted);
console.log("BEFORE: ", payload_adv);
const sorted_adv = sort(payload_adv, (left, right) => left.num - right.num);
console.log("AFTER: ", sorted_adv);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment