+ 4
Help Debug a Java Merge Sort implementation
I created a Merge Sort implementation in Java, However, it seems to have a bug that's throwing an Index Out of Bounds Exception.
5 Respuestas
+ 3
William Mabotja
Your code not suitable for merge sort
As you know,
Merge sort is Algorithm for sorting elements in ascending order.
And also it works like a divide and conquer approach (I.e.,first divided and next merge).your code works fine until it divides the left subpart of your elements.
Take a look at your array of elements
[ 5,8,1,4,7,3,9,0,2,6 ] length is 10 --->n
In first iteration:
n=10;
m=10/2 =5; left array [5,8,1,4,7]
right array[3,9,0,2,6]
In second iteration:
n=5;
m=5/2=2; left array [5,8]
right array[1,4,7]
In third iteration:
n=2; left array[5]
m=2/2=1; right array[8]
In fourth iteration:
n=1 (n<2) as per your condition it fail
m=1
now it calls to Merge() method with parameters
it does not divide right part of your array.
+ 3
William Mabotja provide a complete solution
try your code in code playground and save it and paste link here
+ 2
Thank you Navya, You've been helpful, I will try fix it with your advice in hand, Namaste
+ 1
William Mabotja
My pleasure to help you