归并排序:合并有序数列
归并排序步骤:
1.将一个数组拆分成两份(从中间拆开)。
定义最左侧指针为low,右侧为high,中间指针mid=(low+high)/2
2.然后通过递归的方法继续拆分
3.将数组分成一个个的数,然后按顺序合并
(以一半为例分)
(以整个为例分)
(分加合并)
(动图演示)
代码如下(代码注释可以参考)
package com.qcby;
import java.util.Arrays;
public class gui {
public static void main(String[] args) {
int arr[] = {6,5,3,1,8,7,2,4};
System.out.println("排序前结果:" + Arrays.toString(arr));
mergeSort(arr, 0, arr.length - 1);
System.out.println("排序后结果:" + Arrays.toString(arr));
}
//分
public static void mergeSort(int[] arr, int low, int high) {
//首先判断 low 和 high是否指向一个地方
// 正常情况下就是 ==
if(low == high) {
return;
}
int mid = (low + high)/2;
//先递归左边
mergeSort(arr, low, mid);
//在递归右边
mergeSort(arr, mid+1, high);
//合并
merge(arr,low,mid,high);
}
//合并
public static void merge(int[] a, int low, int mid, int high) {
//定义第一个段的开始
int s1 = low;
//定义第二个段的开始
int s2 = mid+1;
//定义临时数组
int[] temp = new int[high-low+1];
int i = 0;//定义临时数组的下标
//判断大小将数组放入到临时数组当中去
while(s1<=mid && s2<=high) {
if(a[s1] <= a[s2]) {
temp[i] = a[s1];
i++;
s1++;
}else {
temp[i++] = a[s2++];
}
}
//判断s1当中是否有数据,如果有将其全部拷贝到临时数组当中去
while (s1 <= mid) {
temp[i++] = a[s1++];
}
//判断s2当中是否有数据,如果有将其全部拷贝到临时数组当中去
while (s2 <= high) {
temp[i++] = a[s2++];
}
//将临时数组当中的代码放回原数组
for (int j = 0; j < temp.length; j++) {
a[j+low] = temp[j];
}
}
}