算法思想:把待排数列分成两部分,排序每一部分,然后将排序后的两部分合并。递归地进行这个过程。
时间复杂度:O(N*logN)
代码:
import java.util.*;
class mergeSort {
public static int[] sort(int[] theArray, int lowerBound, int higherBound) {
int mid = (lowerBound + higherBound) / 2;
if (lowerBound < higherBound) {
sort(theArray, lowerBound, mid);
sort(theArray, mid + 1, higherBound);
merge(theArray, lowerBound, mid, higherBound);
}
return theArray;
}
public static void merge(int[] theArray, int lowerBound, int mid, int higherBound) {
int[] temp = new int[higherBound - lowerBound + 1];
int i = lowerBound;
int j = mid + 1;
int k = 0;
while (i <= mid && j <= higherBound) {
if (theArray[i] < theArray[j]) {
temp[k++] = theArray[i++];
} else {
temp[k++] = theArray[j++];
}
}
while (i <= mid) {
temp[k++] = theArray[i++];
}
while (j <= higherBound) {
temp[k++] = theArray[j++];
}
for (int k2 = 0; k2 < temp.length; k2++) {
theArray[k2 + lowerBound] = temp[k2];
}
}
public static void main(String[] args) {
int[] theArray = {10,90,87,67,19,67,23,44,15,111,123,54,1234,1024};
mergeSort.sort(theArray, 0, theArray.length-1);
System.out.println(Arrays.toString(theArray));
}
}