package Recursive_Algorithm;
import java.util.Arrays;
public class MergeSort {
int len = 20;
int arr [] = new int[len];
public MergeSort(){
for(int i = 0;i < len;i++){
arr[i] = (int)(Math.random() * len);
}
}
public MergeSort(int len){
arr = new int[len];
for(int i = 0;i < len;i++){
arr[i] = (int)(Math.random() * len);
}
}
public MergeSort(int[] arr){
this.arr = arr;
}
public int[] mergeSort(int[] arr,int L,int R) {
int mid = L + ((R - L) >> 1);
if (R - L == 0) {
int[] arr1 = new int[1];
arr1[0] = arr[L];
return arr1;
}
int[] arr_L = mergeSort(arr,L, mid);
int[] arr_R = mergeSort(arr,mid + 1, R);
int i = 0;
int j = 0;
int[] arr1 = new int[R - L + 1];
for (int k = 0; k <= R - L; k++) {
if (i < arr_L.length && j < arr_R.length && L < R){
arr1[k] = arr_L[i] > arr_R[j] ? arr_R[j++] : arr_L[i++];
}
else if (i < arr_L.length && j >= arr_R.length){
arr1[k] = arr_L[i++];
}
else if (i >= arr_L.length && j < arr_R.length){
arr1[k] = arr_R[j++];
}
}
return arr1;
}
public static void main(String[] args) {
// int [] arr = {1,3,5,2,6};
MergeSort mergesort = new MergeSort(90);
// MergeSort mergesort = new MergeSort(arr);
int [] arr = mergesort.arr;
arr = mergesort.mergeSort(mergesort.arr,0,arr.length - 1);
System.out.println(Arrays.toString(arr));
}
}
输出
[1, 4, 6, 7, 8, 8, 8, 9, 11, 12, 15, 15, 15, 17, 18, 18, 18, 20, 22, 23, 23, 23, 28, 28, 29, 30, 31, 31, 32, 35, 36, 36, 37, 38, 39, 40, 41, 42, 43, 43, 44, 44, 46, 46, 47, 47, 47, 48, 50, 51, 51, 52, 53, 53, 54, 57, 57, 57, 58, 58, 58, 59, 60, 60, 61, 62, 63, 65, 67, 67, 68, 70, 70, 72, 75, 76, 77, 78, 78, 78, 80, 81, 81, 82, 84, 84, 87, 88, 88, 89]