因此,对于输入大小-10、20、30,以下算法可以很好地发挥作用
输入大小-输出中可见35个时滞
输入大小-40您将等待一段时间
大于40的内容-无法完成排序。
public class TestSorting {
public static void main(String[] args) {
long start, end;
Comparable[] numbers = generateRandom(45);
Comparable[] temp;
temp = Arrays.copyOf(numbers,numbers.length);
System.out.println("-----------------------------------------------------------");
System.out.println(" M E R G E S O R T");
System.out.println("-----------------------------------------------------------");
System.out.println("Initial: " + Arrays.asList(temp));
start = System.nanoTime();
Merge.sort(temp);
end = System.nanoTime();
System.out.println("Final : " + Arrays.asList(temp));
System.out.println("Total Runtime: " + (end-start));
}
private static Comparable[] generateRandom(int size) {
Comparable[] data = new Comparable[size];
Random random = new Random();
for(int i = 0 ;i<size;i++)
data[i] = random.nextInt(100);
return data;
}
}
Merge.java
public class Merge {
public static boolean lessThan(Comparable x, Comparable y) {
return x.compareTo(y)<0;
}
public static void sort(Comparable[] data) {
sort(data,0,data.length-1);
}
private static void sort(Comparable[] data,int low,int high) {
if(high<=low) return;
int mid = low + (high-low)/2;
sort(data,0,mid);
sort(data,mid+1,high);
merge(data,low,mid,high);
}
private static void merge(Comparable[] data, int low, int mid, int high) {
Comparable[] X = new Comparable[mid-low+1]
Comparable[] Y = new Comparable[high-mid];
for(int i=0;i<X.length;i++) X[i] = data[low+i];
for(int i=0;i<Y.length;i++) Y[i] = data[mid+1+i];
int start1 = 0, start2 = 0;
while(start1<X.length && start2<Y.length) {
if(lessThan(X[start1],Y[start2])) data[low++] = X[start1++];
else data[low++] = Y[start2++];
}
while (start1 < X.length) data[low++] = X[start1++];
while (start2 < Y.length) data[low++] = Y[start2++];
}
}
任何人都可以帮助我找出问题所在吗? 是因为额外的本地数组创建使它运行缓慢?
答案 0 :(得分:0)
递归调用
sort(data,0,mid);
实际上应该是
sort(data,low,mid);