I made the following code in java for merge sort but in the output I'm getting output: -
0 0 0 0 0 0
I have tried debugging it for the past two hours. Where am I going wrong here?
public class MergeSort {
public static void Mergesort(int[] a){
int n=a.length;
if(n<2)
return;
int mid=n/2;
int[] left=new int[mid];
int[] right=new int[n-mid];
for(int i=0;i<mid-1;i++)
{left[i]=a[i];}
for(int i=mid;i<n-1;i++)
{right[i-mid]=a[i];}
Mergesort(left);
Mergesort(right);
merge(left,right,a);
}
public static void merge(int[]x,int[] y,int[] z){
int p=x.length;
int q=y.length;
int i=0;int j=0;int k=0;
while(i<p&&j<q){
if(x[i]<=y[j])
z[k++]=x[i++];
else
z[k++]=y[j++];
}
while(i<p) z[k++]=x[i++];
while(j<q) z[k++]=y[j++];
}
public static void main(String[] args) {
int[] arr={9,10,8,5,1,0};
Mergesort(arr);
for(int l=0;l<arr.length;l++)
{System.out.println(arr[l]);}
}
}
Output is 0 0 0 0 0 0
I think there is something wrong with the partitioning !
Using the debugger I can see that
for(int i=0;i<mid-1;i++)
and
for(int i=mid;i<n-1;i++)
should be
for(int i = 0; i < mid; i++)
and
for(int i = mid; i < n; i++)
Your code doesn't copy the last element and eventually you just have all 0's
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.