归并排序
代码:
public class Code04_MergeSort {
public static int[] arr = {3,5,8,6,1,2,9,7,4,0};
public static void merge(int L, int mid, int R) {
int[] temp = new int[R-L+1]; //辅助数组
System.out.println(R + " " + L + " " + mid);
int p1 = L, p2 = mid+1, idx = 0;
while (p1 <= mid && p2 <= R) {
if (arr[p1] <= arr[p2]) {
temp[idx++] = arr[p1++];
} else {
temp[idx++] = arr[p2++];
}
}
while (p1 <= mid) {
System.out.println(idx);
temp[idx++] = arr[p1++];
}
while (p2 <= R) {
temp[idx++] = arr[p2++];
}
for (int i = 0; i < temp.length; i++) {
arr[L + i] = temp[i];
}
}
public static void mergeSort(int L, int R) {
if (L >= R) {
return;
}
int mid = (L+R)/2;
mergeSort(L, mid);
mergeSort(mid+1, R);
merge(L, mid, R);
}
public static void main(String[] args) {
System.out.println(arr);
mergeSort(0, 9);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
}
}
}