I am trying to write merge sort algorithm myself in javascript but is see that it is not working. I am taking a sample array [9,1,5,3] and trying to sort it. But it is giving me incorrect result but console shows me [3, undefined, undefined, 5]. I am unable to figure out myself where ut is going wrong.Can anyone help me in this
function merge(arr,start, mid,end){
const result=[];
let first=start;
let index=start;
let midNext= mid+1;
while(first<=mid && midNext<=end){
if(arr[first]<=arr[midNext]){
result[index++]=arr[first++]
}else{
result[index++]=arr[midNext++]
console.log(result)
}
while(first<=mid){
result[index++]=arr[first++]
console.log(result)
}
while(midNext<=end){
result[index++]=arr[midNext++]
console.log(result)
}
}
for(let i=0;i<=end;i++){
arr[i]=result[i];
}
console.log(arr)
}
function mergeSort(arr, start, end){
if(start==end){return start;}
let midIndex=Math.floor( start+ (end-start)/2);
mergeSort(arr,start,midIndex);
mergeSort(arr,midIndex+1,end);
merge(arr,start,midIndex, end)
}```