Java 二路归并算法
我自己写出来的时间复杂度没那么小,从网上看了一个归并算法,谁可以帮我解释一下。。。。希望有大侠不吝赐教。。。。
鄙人不胜感激。。。。
public class debug {
public static void merge(int[] data, int p, int q, int r) {
int[] B = new int[data.length];
int s = p;
int t = q + 1;
int k = p;
while (s <= q && t <= r) {
if (data[s] <= data[t]) {
B[k] = data[s];
s++;
} else {
B[k] = data[t];
t++;
}
k++;
}
if (s == q + 1) {
B[k++] = data[t++];
} else {
B[k++] = data[s++];
}
for (int i = p; i <= r; i++) {
data[i] = B[i];
}
}//end merge
public static void merge_sort(int[] data, int left, int right) {
int t = 1;// 每组元素个数
int size = right - left + 1;
while (t < size) {
int s = t;// 本次循环每组元素个数
t = 2 * s;
int i = left;
while (i + (t - 1) < size) {
merge(data, i, i + (s - 1), i + (t - 1));
i = i + t;
}
if (i + (s - 1) < right) {
merge(data, i, i + (s - 1), right);
}
}
}
public static void main(String [] args)
{
int a[] = {1,9,2,5,4,3,7,6,8,0};
merge_sort(a,0,9);
for(int i =0 ;i<=9;i++)
System.out.print(a[i]+",");
}
}
----------------解决方案--------------------------------------------------------