MergingSort 复习笔记
package sort;
import java.util.Arrays;
public class MergingSort {
public static void main(String[] args) {
int[] list = new int[]{2, 2, 3, 1, 5, 7, 4, 6, 9, 8};
int[] temp = new int[list.length];
System.out.println("排序前:"+Arrays.toString(list));
mergeSort(list, 0, list.length - 1, temp);
System.out.println("排序后:"+Arrays.toString(list));
}
public static void mergeSort(int[] list, int left, int right, int[] templist) {
if (left < right) {
int mid = (left + right) / 2;
mergeSort(list, left, mid, templist);
mergeSort(list, mid + 1, right, templist);
merge(list, left, mid, right, templist);
}
}
public static void merge(int[] list, int left, int mid, int right, int[] temp) {
int i = left;
int j = mid + 1;
int t = 0;
while (i <= mid && j <= right) {
if (list[i] < list[j]) {
temp[t] = list[i];
t++;
i++;
} else {
temp[t] = list[j];
t++;
j++;
}
}
while (i <= mid) {
temp[t] = list[i];
t++;
i++;
}
while (j <= right) {
temp[t] = list[j];
t++;
j++;
}
t = 0;
int tempLeft = left;
while (tempLeft <= right){
list[tempLeft] = temp[t];
t++;
tempLeft++;
}
}
}