Sample 1:
function mergesort(arr){
if (arr.length > 1){
let mid = parseInt(arr.length/2);
let left = arr.slice(0,mid);
let right = arr.slice(mid);
mergesort(left);
mergesort(right);
return merge(left,right);
}
else return arr;
}
Sample 2:
function mergesort(arr){
if (arr.length > 1){
let mid = parseInt(arr.length/2);
let left = mergesort(arr.slice(0,mid));
let right = mergesort(arr.slice(mid));
return merge(left,right);
}
else return arr;
}
Merge function:
function merge(left, right){
let leftIdx = 0, rightIdx = 0;
const result = [];
while (leftIdx < left.length && rightIdx < right.length){
if (left[leftIdx] < right[rightIdx]){
result.push(left[leftIdx++])
}
else{
result.push(right[rightIdx++])
}
}
let res = [...result, ...left.slice(leftIdx), ...right.slice(rightIdx)];
return res;
Sample 2 is giving the correct output but sample 1 is not. Can you explain the difference between both samples?
let arr = [5, 3, 7, 2, 9, 12, 4];
Applying sample 1 on arr gives [2, 5, 3, 7, 9, 12, 4] as output that is obviously incorrect.
3
Answers
You have to change these two lines
to
Otherwise you are continuing to work with the unsorted arrays.
Your first code sample does not work because you did not assign the output of
mergesort
to a new variable.Try it like this instead:
The difference between the two samples lies in how the
left
andright
arrays are created and passed recursively in themergesort
function.In sample 1, the
left
andright
arrays are created using thearr.slice()
method after finding the midpoint. Then,mergesort
is called recursively onleft
andright
. However, the resulting sorted arrays from these recursive calls are not assigned to any variables. Therefore, whenmerge(left, right)
is called, it operates on the originalleft
andright
arrays, which are still unsorted. This leads to an incorrect result.In sample 2, the
left
andright
arrays are created using themergesort(arr.slice())
calls directly when assigning them to variables. This means that the recursive calls return the sorted arrays, which are then properly assigned toleft
andright
. Consequently, whenmerge(left, right)
is called, it operates on the correctly sorted arrays, resulting in the correct output.To fix sample 1, you would need to assign the returned values of the recursive
mergesort
calls toleft
andright
before callingmerge(left, right)
.Here’s an updated version of sample 1:
With this modification, both sample 1 and sample 2 should produce the correct output. MADE WITH THE HELP OF CHAT GPT.