Bug in code for mergesort

what is the bug in mergesort algo.

Make 2 functions. One which splits the array in two parts and calls the other function which merges the two sorted parts.

@S19APP-PP0108
but I want to do in same function only…in past I did that but this time I am not able to find my own mistake !
What is the issue where my logic is failing ?

Actually, this way reduces the readability of your code and makes it prone to errors. I suggest you take a smaller array and dry run your code on it.

@S19APP-PP0108
hello
I am more comfortable this way (specifically for mergesort) … Please just correct my code in the link shared previously
I tried dry run for short arrays and I couldn’t find error in logic

  1. In line 4, return if i>=j.
  2. In if statement of line 6, you should return even if a[i]<a[j]. No need to execute statements after that.
  3. In your function, use variables other than the ones declared in the function parameters: like i in for loop in line 16.
  4. Also, there is no need to take an entirely new array of range n because the mapping then should be same in both the arrays. If you are referring to elements in your array a from index i to j, this should be same in your array arr as well. You can’t start from 0 then.
    Instead, make two new arrays of size (mid-i+1) and (j-mid). And then insert the elements and do a similar process.
1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.