import java.util.Arrays;
public class MergeSort {
public static void mergeSort(int[] arrays, int left, int right) {
if (left < right) {
int middle = (left + right) / 2;
mergeSort(arrays, left, middle);
mergeSort(arrays, middle + 1, right);
merge(arrays, left, middle, right);
}
}
public static void merge(int[] arr, int left, int middle, int right) {
int[] temp = new int[right - left + 1];
int i = left;
int j = middle + 1;
int k = 0;
while (i <= middle && j <= right) {
if (arr[i] < arr[j]) {
temp[k++] = arr[i++];
} else {
temp[k++] = arr[j++];
}
}
while (i <= middle) {
temp[k++] = arr[i++];
}
while (j <= right) {
temp[k++] = arr[j++];
}
for (int l = 0; l < temp.length; l++) {
arr[l + left] = temp[l];
}
}
public static void main(String[] args) {
int[] ints = {5, 3, 4, 1, 2};
mergeSort(ints,0,ints.length-1);
System.out.println(Arrays.toString(ints));
}
}
转载请注明原文地址:https://ipadbbs.8miu.com/read-891.html