Question: Having trouble with writing a method msort. It is supposed to recusively sort an array of objects using the merge sort algorithim and specifically can

Having trouble with writing a method msort. It is supposed to recusively sort an array of objects using the merge sort algorithim and specifically can only pass an array as a parameter and calls merge (which specifcally has to pass two arrays as parameters) to merge to subarrays. The output shows the arrays not being properly sorted. Not sure what is wrong.

public static void mergesort(Comparable[] a)

{

msort(a);

}

public static Comparable[] msort(Comparable[] a)

{

int min = 0; // minimum index

int max = a.length-1; // maximum index

int k = 0;

Comparable[] result = null;

if(min < max)

{

int mid = (min + max) /2; // middle index

Comparable[] b = Arrays.copyOfRange(a, 0, mid);

Comparable[] c = Arrays.copyOfRange(a, mid+1, max);

msort(b);

msort(c);

result = merge(b,c);

}

return result;

}

public static Comparable[] merge(Comparable[] a, Comparable[] b)

{

int size = a.length + b.length;

Comparable[] result = new Comparable[size];

int i = 0;

int j = 0;

int k = 0;

while(i < a.length && j < b.length)

{

if(a[i].compareTo(b[j]) < 0)

{

result[k] = a[i];

i++;

}

else

{

result[k] = b[j];

j++;

}

k++;

}

while(i < a.length)

{

result[k] = a[i];

i++;

k++;

}

while(i < b.length)

{

result[k] = b[j];

j++;

k++;

}

return result;

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!