For my homework in java, I am struggling to write a recursive merge sort class. At the moment, I have 3 driver methods to trigger recursion, a recursive method, mergeSortand a method merge. Depending on which variables are changing, my output is either an array of all zeros, or my original array in the same order. The only thing that the original method mergeSortshould take in one array, and the method mergecan not return anything. Any help with a great rating
import java.util.Arrays;
public class merge2 {
public static void main(String[] args){
int []a={22,45,1,4,89,7,0};
mergeSort(a);
System.out.println(Arrays.toString(a));
}
public static void mergeSort(int [] a){
mergeSort(a,0,a.length-1);
}
public static void mergeSort(int []a, int beg,int end){
if(beg<end){
int mid=(beg+end)/2;
mergeSort(a,beg,mid);
mergeSort(a,mid+1,end);
merge(a,beg,mid,end);
}
}
private static void merge(int []a, int beg, int middle, int end){
int [] d=new int[a.length];
int mid=middle+1;
for(int i=0;i<d.length;i++){
if(beg<=middle && mid<=end){
if(a[beg]<=a[mid]) {
d[i]=a[beg];
beg++;
} else if(a[mid]<=a[beg]){
d[i]=a[mid];
mid++;
}
}else if(beg>middle){
d[i]=a[mid];
mid++;
}else if(mid==a.length){
d[i]=a[beg];
beg++;
}
}
for(int w=0;w<d.length;w++){
a[w]=d[w];
}
}
}
source
share