implement merge sort javascript code example
Example 1: merge sort javascript
function mergeSort (unsortedArray) {
if (unsortedArray.length <= 1) {
return unsortedArray;
}
const middle = Math.floor(unsortedArray.length / 2);
const left = unsortedArray.slice(0, middle);
const right = unsortedArray.slice(middle);
return merge(
mergeSort(left),
mergeSort(right)
);
}
function merge (left, right) {
let resultArray = [], leftIndex = 0, rightIndex = 0;
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] < right[rightIndex]) {
resultArray.push(left[leftIndex]);
leftIndex++;
} else {
resultArray.push(right[rightIndex]);
rightIndex++;
}
}
return resultArray
.concat(left.slice(leftIndex))
.concat(right.slice(rightIndex));
}
Example 2: array sorting javascript mergesort
function mergeSort (unsortedArray) {
if (unsortedArray.length <= 1) {
return unsortedArray;
}
const middle = Math.floor(unsortedArray.length / 2);
const left = unsortedArray.slice(0, middle);
const right = unsortedArray.slice(middle);
return merge(
mergeSort(left), mergeSort(right)
);
}
Example 3: implement a merge sort algorithm JS
function merge(left, right) {
const resultArray = []
let leftIndex = 0
let rightIndex = 0
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] < right[rightIndex]) {
resultArray.push(left[leftIndex])
leftIndex+=1
} else {
resultArray.push(right[rightIndex])
rightIndex+=1
}
}
return resultArray
.concat(left.slice(leftIndex))
.concat(right.slice(rightIndex))
}
function mergeSort(unsortedArray) {
if (unsortedArray.length <= 1) {
return unsortedArray;
}
const middle = Math.floor(unsortedArray.length / 2);
const left = unsortedArray.slice(0, middle);
const right = unsortedArray.slice(middle);
return merge(
mergeSort(left), mergeSort(right)
);
}
mergeSort([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])