归并排序的时间复杂度(O(n log n))要高于一般的排序算法,如冒泡等(O(n^2));
具体实现如下:
public class MergeSort {
public static void main(String[] args) {
int[] array = {6, 1, 7, 9, 4, 3, 5};
MergeSort sort = new MergeSort();
int[] temp = new int[array.length];
sort.mergeSort(array, 0, array.length - 1, temp);
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
private void mergeSort(int[] array, int start, int end, int[] temp) {
int mid = start + (end - start) / 2;
if (start >= end) return;
mergeSort(array, start, mid, temp);
mergeSort(array, mid + 1, end, temp);
sort(array, start, mid, end, temp);
}
private void sort(int[] array, int start, int mid, int end, int[] temp) {
int i = start;
int j = mid + 1;
int k = 0;
while (i <= mid && j <= end) {
if (array[i] > array[j]) {
temp[k++] = array[j++];
} else {
temp[k++] = array[i++];
}
}
while (i <= mid) {
temp[k++] = array[i++];
}
while (j <= end) {
temp[k++] = array[j++];
}
k = 0;
while (start <= end) {
array[start++] = temp[k++];
}
}
}