extra storage merge sort
Posted
by davit-datuashvili
on Stack Overflow
See other posts from Stack Overflow
or by davit-datuashvili
Published on 2010-05-18T21:01:48Z
Indexed on
2010/05/18
23:40 UTC
Read the original article
Hit count: 158
I need make a merge sort using an additional array. Here is my code:
public class extra_storage{
public static void main(String[]args) {
int x[]=new int[]{12,9,4,99,120,1,3,10};
int a[]=new int[x.length];
mergesort(x,0,x.length-1,a);
for (int i=0;i<x.length;i++){
System.out.println(x[i]);
}
}
public static void mergesort(int x[],int low,int high, int a[]){
if (low>=high) {
return;
}
int middle=(low+high)/2;
mergesort(x,low,middle,a);
mergesort(x,middle+1,high,a);
int k;
int lo=low;
int h=high;
for (k=low;k<high;k++)
if ((lo<=middle ) && ((h>high)||(x[lo]<x[h]))){
a[k]=x[lo++];
}
else {
a[k]=x[h++];
}
for (k=low;k<=high;k++){
x[k]=a[k];
}
}
}
But something is wrong. When I run it the output is this:
1 0 3 0 4 0 9 0
What is the problem?
© Stack Overflow or respective owner