思想
归并排序(Merge Sort)是建立在归并操作上的一种有效,稳定的排序算法,该算法是采用分治法的一个非常典型的应用。将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。若将两个有序表合并成一个有序表,称为二路归并。
code
public class Code_04_MergeSort {
public static void mergeSort(int[] arr) {
if (arr == null || arr.length < 2) {
return;
}
mergeSort(arr, 0, arr.length - 1);
}
public static void mergeSort(int[] arr, int left, int right) {
if (left == right) {
return;
}
int mid = (left + right) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
public static void merge(int[] arr, int left, int mid, int right) {
int[] temp = new int[right - left + 1];
int i = 0;
int p1 = left;
int p2 = mid + 1;
while (p1 <= mid && p2 <= right) {
temp[i++] = arr[p1] < arr[p2] ? arr[p1++] : arr[p2++];
}
while (p1 <= mid){
temp[i++] = arr[p1++];
}
while (p2 <= right){
temp[i++] = arr[p2++];
}
for (int j = 0; j < temp.length; j++) {
arr[left + j] = temp[j];
}
}
public static void main(String[] args) {
int testTime = 500000;
int maxSize = 100;
int maxValue = 100;
boolean succeed = true;
for (int i = 0; i < testTime; i++) {
int[] array = Code_01_BubbleSort.generateRandomArray(maxSize, maxValue);
int[] array1 = Code_01_BubbleSort.copyArray(array);
int[] array2 = Code_01_BubbleSort.copyArray(array);
mergeSort(array1);
Code_01_BubbleSort.comparator(array2);
if (!Code_01_BubbleSort.isEqual(array1, array2)){
succeed = false;
break;
}
}
System.out.println(succeed ? "nice" : "dddd");
// int[] temp = Code_01_BubbleSort.generateRandomArray(maxSize,maxValue);
// mergeSort(temp);
// Code_01_BubbleSort.printArray(temp);
}
}