@Author:云都小生
概述
今天我们要来学习一个排序的算法——归并排序。个人觉得,理解起来算是比较容易的,但是要用代码去实现,就比较难了。
归并排序主要分为两个部分,第一个部分是分解,第二个部分是排序。
归并排序的算法思想是:每次将序列分解,最后分解成长度为1的多个自序列,然后再两两归并排序,最后得到一个长度为n的有序序列。
如下图:
代码实现
import java.util.Arrays;
public class MergeSort {
public static void main(String[] args) {
int a[] = new int[]{5,2,0,6,19,7,3,1,8,4};
mergeSort(a,0,9);
System.out.println("排序后:" + Arrays.toString(a));
}
//分解
private static void mergeSort(int[] a, int low,int high)
{
int mid = (low+high)/2;
if(low < high) //如果剩下一个,就不能再进行分解了
{
mergeSort(a,low,mid); //对左边进行分解、递归
mergeSort(a,mid+1,high); //对右边进行分解、递归
merge(a,low,mid,high); //进行排序
System.out.println(Arrays.toString(a));
}
}
//归并
public static void merge(int[] a, int low, int mid, int high) {
int[] temp = new int[high - low + 1];
int i = low;
int j = mid + 1;
int k = 0;
//把较小的数先移到新数组中
while (i <= mid && j <= high) {
if (a[i] < a[j]) {
temp[k++] = a[i++];
} else {
temp[k++] = a[j++];
}
}
//如果左边有剩下的,就移入数组
while (i <= mid) {
temp[k++] = a[i++];
}
//如果右边有剩下的,就移入数组
while (j <= high) {
temp[k++] = a[j++];
}
//把新数组中的数覆盖nums数组
for (int x = 0; x < temp.length; x++) {
a[x + low] = temp[x];
}
}
}
2017/11/12 23:17:38 @Author:云都小生