两种排序都是用的是divide and conquer的思想,时间复杂度都是O(nlogn).
归并排序的难点在merge部分,T(n) = 2(n/2) + n, 所以复杂度是O(nlogn)
public static void mergeSort(int[] A){
if(A == null || A.length <= 1) return;
mergeSort2(A, 0, A.length - 1);
}
private static void mergeSort2(int[] A, int start, int end){
if(start < end){
int mid = (start + end) / 2;
mergeSort2(A, start, mid);
mergeSort2(A, mid + 1, end);
merge(A, start, mid, end);
}
}
private static void merge(int[] A, int start, int mid, int end){
int[] temp = new int[end - start + 1];
int i = start, j = mid + 1, k = 0;
while(i <= mid && j <= end){
if(A[i] <= A[j]){
temp[k++] = A[i++];
} else {
temp[k++] = A[j++];
}
}
while(i <= mid){
temp[k++] = A[i++];
}
while(j <= end){
temp[k++] = A[j++];
}
for(int p = 0; p < temp.length; p++){
A[start++] = temp[p];
}
}
public static void quickSort(int[] A){
if(A == null || A.length <= 1) return;
quickSort2(A, 0, A.length - 1);
}
private static void quickSort2(int[] A, int start, int end){
if(start < end){
int i = start, j = end, pivot = A[start];
while(i < j){
while(i < j && A[j] >= pivot){
j--;
}
while(i < j && A[i] <= pivot){
i++;
}
if(i < j){
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}
A[start] = A[i];
A[i] = pivot;
quickSort2(A, start, i - 1);
quickSort2(A, i + 1, end);
}
}