归并排序算法
代码语言:javascript
复制/**
* 归并排序
*/
public class MergeSort {
public static void mergeSort(int[] arr, int l, int r){
if(l >= r){
return;
}
int mid = (l r) / 2;
mergeSort(arr, l, mid);
mergeSort(arr, mid 1, r);
merge(arr, l, mid, r);
}
public static void merge(int[] arr, int l, int m, int r){
int[] tmp = new int[r - l 1];
for (int i = 0;i<tmp.length;i ) {
tmp[i] = arr[l i];
}
int i = l,j = m 1;
for(int k = l; k <= r; k ){
if(i > m){
arr[k] = tmp[j - l];
j ;
} else if(j > r){
arr[k] = tmp[i - l];
i ;
} else if(tmp[i - l] > tmp[j - l]){
arr[k] = tmp[i - l];
i ;
} else {
arr[k] = tmp[j - l];
j ;
}
}
}
public static void main(String[] args) {
int[] arr = {2,4,5,3,1,8,1,4,3};
mergeSort(arr, 0, arr.length - 1);
System.out.println(Arrays.toString(arr));
}
}