Skip to content

Instantly share code, notes, and snippets.

@mustafadalga
Created November 23, 2021 14:54
Show Gist options
  • Save mustafadalga/8cbdab88bad39e10d707e583821b13f9 to your computer and use it in GitHub Desktop.
Save mustafadalga/8cbdab88bad39e10d707e583821b13f9 to your computer and use it in GitHub Desktop.
Merge Sort Algorithm Example
function merge(firstArray, secondArray) {
let results = [], firstArrayIndex = 0, secondArrayIndex = 0;
while (firstArrayIndex < firstArray.length && secondArrayIndex < secondArray.length) {
if (secondArray[secondArrayIndex] > firstArray[firstArrayIndex]) {
results.push(firstArray[firstArrayIndex])
firstArrayIndex++;
} else {
results.push(secondArray[secondArrayIndex])
secondArrayIndex++;
}
}
while (firstArrayIndex < firstArray.length) {
results.push(firstArray[firstArrayIndex]);
firstArrayIndex++;
}
while (secondArrayIndex < secondArray.length) {
results.push(secondArray[secondArrayIndex]);
secondArrayIndex++;
}
return results;
}
function mergeSort(arr) {
if (arr.length <= 1) return arr;
let mid = Math.floor(arr.length / 2);
let left = mergeSort(arr.slice(0, mid));
let right = mergeSort(arr.slice(mid));
return merge(left, right);
}
const numberList = [...new Set(Array.from({ length: 50 }, () => Math.floor(Math.random() * 250)))];
console.log(mergeSort(numberList))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment