Skip to content

Instantly share code, notes, and snippets.

@fortunee
Last active March 14, 2023 01:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fortunee/27733d4bb8999abcdb1fca1ad9c03382 to your computer and use it in GitHub Desktop.
Save fortunee/27733d4bb8999abcdb1fca1ad9c03382 to your computer and use it in GitHub Desktop.
Merge sort basically splits, sorts and merges the values in the array
/**
* PSEUDOCODE
* - Break up the array into halves until you have an empty array or array with one element
* - Once you have the smaller sorted arrays, merge those arrays with other sorted arrays until
* - you are back at the full length of the array
* - Once the array has been merged back together return the merged and sorted array
*/
function mergeSort(array) {
if (array.length <= 1) return array;
const middlePoint = Math.floor(array.length / 2);
const leftPortion = mergeSort(array.slice(0, middlePoint));
const rightPortion = mergeSort(array.slice(middlePoint));
return merge(leftPortion, rightPortion);
}
/**
* PSEUDOCODE (merge helper function)
* - Create an empty array called merged
* - Look for the smallest values in each input array (ie. if sorting ASC order)
* - While there are still values we haven't looked at
* - if the value in the first array is smaller than the value in the second array, push
* - the value in the first array into the merged array and move onto the next value in the first array.
* - if the value in the first array is larger than the value in the second array, push the value
* - in the second array into the merged array and move on to the next value in the second array
* - Once we exhaust one array, push in all remaining values from the other array
*/
function merge(array1, array2) {
const merged = [];
let i = 0;
let j = 0;
while (i < array1.length && j < array2.length) {
if (array1[i] < array2[j]) {
merged.push(array1[i])
i++;
} else {
merged.push(array2[j])
j++;
}
}
while (i < array1.length) {
merged.push(array1[i])
i++;
}
while (j < array2.length) {
merged.push(array2[j])
j++;
}
return merged;
}
mergeSort([8, 32, 5, 32, 3, 100, 11])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment