归并排序的时间复杂度为O(nlogn)
它采用的是分治法的思想,先将序列拆分为1个个子序列,直到每个序列的长度为1,此时每个序列都是有序的;然后将两个有序的子序列合并成为一个更大的子序列,递归此过程,直到子序列的长度和原序列相同,此时排序完成,图示如下:
具体代码如下:
import java.util.Arrays;
/**
* Created by 亮大王 on 2017/8/31.
*/
public class no2 {
public static void main(String[] args) {
int a[] = {49, 38, 65, 97, 76, 13, 27};
System.out.println(Arrays.toString(a));
no2 nn = new no2();
nn.mergeSort(a, 0, a.length - 1);
System.out.println(Arrays.toString(a));
}
/**
* 二路归并
*/
public void mergeArray(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++];
}
System.arraycopy(temp, 0, a, low, temp.length);
}
public void mergeSort(int a[], int low, int high) {
int mid = (high + low) / 2;
if (low < high) {
mergeSort(a, low, mid);
mergeSort(a, mid + 1, high);
mergeArray(a, low, mid, high);
}
}
}