归并排序(Merge sort)是建立在归并操作上的一种有效的排序算法。该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。
分而治之(divide - conquer);每个递归过程涉及三个步骤
public void sort(int[] arr) {
int len = arr.length;
if (len <= 1) return;
int[] temp = new int[len];
sort(arr, 0, len - 1, temp);
}
public void sort(int[] arr, int left, int right, int[] temp) {
if (left == right) return;
int mid = (left + right) / 2;
sort(arr, left, mid, temp);
sort(arr, mid + 1, right, temp);
if (arr[mid]<=arr[mid+1]) return;
marge(arr, left,mid, right, temp);
}
public void marge(int[] arr, int left,int mid, int right, int[] temp){
for (int i = left; i <= right ; i++) {
temp[i] = arr[i];
}
int i = left;
int j = mid + 1;
for(int k = left; k <= right; k++){
if (i == mid + 1){
arr[k] = temp[j];
j++;
} else if(j == right + 1){
arr[k] = temp[i];
i++;
}else if(temp[i] >= temp[j]) {
arr[k] = temp[j];
j++;
} else{
arr[k] = temp[i];
i++;
}
}
}
原文:https://www.cnblogs.com/ilyar1015/p/14683577.html