基本思想
建立在归并操作的基础之上,采用“分治”细想。
复杂度
时间复杂度:O(n log n)
代码实现
采用递归,核心代码:
public class MergeSort {
public void mergeSort(int[] arr,int start,int end){
if(start < end){
int min = (start + end)/2;
mergeSort(arr,start,min);
mergeSort(arr,min +1,end);
merge(arr,start,min,end);
}
}
private void merge(int[] arr, int start, int min, int end) {
int[] temp = new int[arr.length];
int pL = start;
int pR = min+1;
int k = start;
//对左右两部分进行比较排序
while(pL <= min && pR <= end){
if (!(arr[pL] > arr[pR])){
temp[k] = arr[pL];
++k;
++pL;
continue;
}
if (!(arr[pL] < arr[pR])){
temp[k] = arr[pR];
++k;
++pR;
}
}
//如果左指针不大于min,则
while (!(pL > min)){
temp[k] = arr[pL];
k++;
pL++;
}
//如果右指针不大于end,则
while (!(pR > end)){
temp[k] = arr[pR];
k++;
pR++;
}
//copy回原数组
for (int i = start;i <=end;i++){
arr[i] = temp[i];
}
}
}
测试:
import java.util.Arrays;
public class MergeTest {
public static void main(String[] args) {
int[] arr = new int[]{4,2,6,3,1,9,7};
MergeSort sort = new MergeSort();
sort.mergeSort(arr,0,arr.length-1);
System.out.println(Arrays.toString(arr));
}
}
结果:
[1, 2, 3, 4, 6, 7, 9]