简介: 归并排序(MERGE-SORT)是建立在归并操作上的一种有效的排序算法,该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。若将两个有序表合并成一个有序表,称为二路归并。归并排序是一种稳定的排序方法。时间复杂度为O(nlogn)。
public static void mergeSort(int[] a,int left,int right) {
if (left<right) {
// 找出中间索引
int mid = (left+right) / 2;
// 对左边数组进行递归
mergeSort(a,left,mid);
// 对右边数组进行递归
mergeSort(a,mid+1,right);
// 合并
merge(a,left,right);
}
}
public static void merge(int[] a,int left,int right) {
// TODO Auto-generated method stub
int l = left,r = right,index = 0;
int[] temp = new int[r-l+1];
int mid = (l+r) / 2,p=mid+1;
while (l<=mid&&p<=r) {
// 从两个数组中取出最小的放入中间数组
if (a[l]<a[p])
temp[index++] = a[l++];
else
temp[index++] = a[p++];
}
// 剩余部分依次放入中间数组
while(l<=mid) temp[index++] = a[l++];
while(p<=r) temp[index++] = a[p++];
// 将中间数组中的内容复制回 原数组
index = 0;
while (left<=right) a[left++] = temp[index++];
System.out.println(Arrays.toString(a));
}