就是分治
归并排序:是一种空间换时间的算法,主要采用的是递归,时间复杂度是o(n-1)
归并排序就是把找到最小的左边或者右边,找到左边最小的,右边最小的,然后进行排序,然后递归查找更大级别的在把它们排序,需要用到一个临时数组,临时数组存放的是排序之后的数组
public class MergeSort {
public static void main(String[] args) {
int[] arr = {8, 4, 5, 7, 1, 3, 6, 2};
int[] temp = new int[arr.length];
merge(arr, 0, arr.length - 1, temp);
System.out.println("排序之后的结果是:" + Arrays.toString(arr));
//测试花费的时间
int array[] = new int[200000];
for (int i = 0; i < 200000; i++) {
array[i] = (int) (Math.random() * 800000);
}
//开始时间
long time = new Date(System.currentTimeMillis()).getTime();
int[] temp2 = new int[array.length];
merge(array, 0, array.length - 1, temp2);
//结束时间
long time2 = new Date(System.currentTimeMillis()).getTime();
System.out.println((time2 - time) + "毫秒");
}
public static void merge(int[] arr, int left, int right, int[] temp) {
if (left < right) {
int mid = (left + right) / 2;
//向左递归进行排序
merge(arr, left, mid, temp);
//向右进行递归
merge(arr, mid + 1, right, temp);
mergeSort(arr, left, mid, right, temp);
}
}
/**
* 合并方法
*
* @param arr 需要排序的数组
* @param left 左边有序序列的初始索引
* @param mid 中间索引
* @param right 右边的结束索引
* @param temp 临时数组
*/
public static void mergeSort(int[] arr, int left, int mid, int right, int[] temp) {
int i = left;//初始化左边有序序列的初始的索引
int j = mid + 1;//初始化右边有序序列的初始索引
int t = 0;//临时索引,指向temp数组的当前索引
//第一步
//先把左右两边(有序)的数据按照规则填充到temp数组
//直到左右两边的有序序列,直到有一边处理完毕为止
while (i <= mid && j <= right) {
//如果左边的有序序列的当前元素,小于右边的有序序列的元素,就把他加入到临时数组里面去
if (arr[i] <= arr[j]) {
temp[t] = arr[i];
t++;
i++;
} else {//如果不小于的话,把右边的假入临时数组里面去
temp[t] = arr[j];
t++;
j++;
}
}
//第二步
//把剩余的数组填充到临时数组里面
while (i <= mid) {
temp[t] = arr[i];
t += 1;
i += 1;
}
while (j <= right) {
temp[t] = arr[j];
t += 1;
j += 1;
}
//第三步
//将temp数组的元素拷贝到arr,注意并不是每次都拷贝
t = 0;
int tempLeft = left;
while (tempLeft <= right) {
arr[tempLeft] = temp[t];
t++;
tempLeft++;
}
}
}