思路
拆 + 合
代码
public static void mergeSort(int[] arr) {
int[] temp = new int[arr.length];
sort(arr, 0, arr.length-1, temp);
}
public static void sort(int[] arr, int left, int right, int[] temp) {
if(left == right) {
return;
}else{
int mid = left + (right - left) / 2;
sort(arr, left, mid, temp);
sort(arr, mid+1, right, temp);
merge(arr, left, right, temp);
}
}
public static void merge(int[] arr, int left, int right, int[] temp) {
int mid = left + (right - left) / 2;
int i = left, j = mid+1, k = left;
while(i <= mid && j <= right) {
temp[k++] = arr[i] <= arr[j] ? arr[i++] : arr[j++];
}
while(i <= mid) {
temp[k++] = arr[i++];
}
while(j <= right) {
temp[k++] = arr[j++];
}
for(i = left; i <= right; i++) {
arr[i] = temp[i];
}
}
性能分析:
时间复杂度:
最好、最坏、平均:
T
(
n
)
=
2
T
(
n
/
2
)
+
O
(
n
)
⇒
T
(
n
)
=
O
(
n
l
o
g
n
)
T(n) = 2T(n/2) + O(n) \Rightarrow T(n) = O(nlogn)
T(n)=2T(n/2)+O(n)⇒T(n)=O(nlogn)
空间复杂度:
O
(
1
)
O(1)
O(1)
稳定性: 稳定,temp[k++] = arr[i] <= arr[j] ? arr[i++] : arr[j++];
这一句确保数组中相等的两个元素能维持排序前的相对位置。