Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I Have to answer this question on this prewritten code, could someone help? impo

ID: 3567255 • Letter: I

Question

I Have to answer this question on this prewritten code, could someone help?

import java.util.Arrays;
public class MergeSort {

//Here is a test array. You may use it or change it to test with other examples.
public static void main(String[] args){
String[] a = {"apple", "orange", "banana", "pear", "grapefruit"};
System.out.println(Arrays.toString(a));
a = mergeSort(a);
System.out.println(Arrays.toString(a));
}

/*
* This is the recursive sorting method, mergeSort.
* Your task is to implement the merge method described below.
*/
public static String[] mergeSort(String[] a){
if(a.length<2)
return a;
int middle = a.length/2;
String[] left = new int[middle];
String[] right = new int[a.length-middle];
int i=0;
for(i=0; i<middle; i++)
left[i] = a[i];
for(int j=0; j<right.length; j++){
right[j] = a[i];
i++;
}
  
left = mergeSort(left);
right = mergeSort(right);
String[] result = merge(left,right);
return result;
}

/*
* This method merges two sorted arrays. They might be of slightly different lengths.
* The resulting array should be sorted and should contain all values (including duplicates)
* from the original two input arrays.
*/
public static String[] merge(String[] l, String[] r){
//TO BE COMPLETED
  
return null;
}
}

Explanation / Answer

I posted just the //to be completed part. If you want me to post the full program, comment here. Cheers.

public static String[] merge(String[] l, String[] r){
//TO BE COMPLETED
int i=0,j=0,k=0;
int slen = l.length,rlen=r.length;
String[] res = new String[slen + rlen];

while(i<slen && j<rlen){
if(l[i].compareTo(r[j]) >= 0){
res[k] = r[j];
j++;
k++;
}
else if(l[i].compareTo(r[j]) < 0){
res[k] = l[i];
i++;
k++;
}
}

if(i<slen){
while(i<slen){
res[k]=l[i];
k++;
i++;
}
}
if(j<rlen){
while(j<rlen){
res[k] = r[j];
j++;
k++;
}
}
return res;
}