Created
November 23, 2021 14:54
-
-
Save mustafadalga/8cbdab88bad39e10d707e583821b13f9 to your computer and use it in GitHub Desktop.
Merge Sort Algorithm Example
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
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