I have a merge sort implementation in Javascript and in golang. It works properly in golang, however, in javascript it seems to always be off by 1. I've havent found any noticeable errors. I would appreciate any insight on to why its failing
I have tried:
- chaning the
foriteration to start atleftStart - changing the middle element from
Math.floortoMath.ceilandMath.round - merging from
starttomiddle-1andmiddletoend
function mergeSort(arr) {
merge(arr, 0, arr.length - 1, []);
}
function merge(arr, start, end, temp) {
if (start >= end) {
return;
}
const middle = Math.floor((start + end) / 2);
merge(arr, start, middle, temp);
merge(arr, middle + 1, end, temp);
mergeHalves(arr, start, end, temp);
}
function mergeHalves(arr, leftStart, rightEnd, temp) {
const leftEnd = Math.floor((leftStart + rightEnd) / 2);
const rightStart = leftEnd + 1;
const size = rightEnd - leftStart + 1;
let left = leftStart;
let right = rightStart;
let index = left;
while (left <= leftEnd && right <= rightEnd) {
if (arr[left] <= arr[right]) {
temp[index] = arr[left];
left++;
} else {
temp[index] = arr[right];
right++;
}
index++;
}
while (left <= leftEnd) {
temp[index] = arr[left];
index++;
left++;
}
while (right <= rightEnd) {
temp[index] = arr[right];
index++;
right++;
}
for (let i = 0; i < size; i++) {
arr[i] = temp[i];
}
}
Test case:
const arr = [2, 1, 3, 5, 6, 2, 7];
mergeSort(arr);
//coming back as [1, 2, 3, 5, 6, 2, 7]
expect(arr).toEqual([1, 2, 2, 3, 5, 6, 7]);