归并排序也是一种常见的排序算法,下面就让我们简单看一下归并排序的实现。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
//将给定区间的数组通过新的数组temp进行排序
public
static
void
merge(
int
[] array,
int
[] temp,
int
leftPos,
int
rightPos,
int
rightEnd) {
int
leftEnd = rightPos -
1
;
int
tempPos = leftPos;
int
length = rightEnd - leftPos +
1
;
//主要的循环操作
while
(leftPos <= leftEnd && rightPos <= rightEnd) {
if
(array[leftPos] <= array[rightPos]) {
temp[tempPos++] = array[leftPos++];
}
else
{
//当leftPos追上rightPos的时候就代表left已经完成排序,而right的剩下值仍需继续排序。
temp[tempPos++] = array[rightPos++];
}
}
while
(leftPos <= leftEnd) {
temp[tempPos++] = array[leftPos++];
}
while
(rightPos <= rightEnd) {
temp[tempPos++] = array[rightPos++];
}
//因为array并不一定是从0开始逐渐进行归并的,所以不能用array[i]=temp[i],只能从结果往前逐渐赋值回去
for
(
int
i =
0
; i < length; i++, rightEnd--) {
array[rightEnd] = temp[rightEnd];
}
}
public
static
void
sort(
int
[] array,
int
[] temp,
int
left,
int
right) {
if
(left < right) {
int
center = (left + right) /
2
;
//不断的递归
sort(array, temp, left, center);
sort(array, temp, center +
1
, right);
merge(array, temp, left, center +
1
, right);
}
}
public
static
void
mergeSort(
int
[] array) {
int
[] temp =
new
int
[array.length];
sort(array, temp,
0
, array.length -
1
);
}
|
最优时间复杂度:O(n)
平均时间复杂度:O(nlog(n))
最坏时间复杂度:O(nlog(n))
平均空间复杂度:O(n),网上有网友猜测归并排序的空间复杂度,有的说是O(n+logn),有的说是O(n),在这里我认为在递归条件下去进行排序的话,应该是O(n+logn),logn是递归栈深度,n是申请的数组。。。非递归的话就是n了。。不知道这种理解是否正确,还望指正。
因为在归并排序的过程中我们不会交换两个一样的数字的位置(没人这么蛋疼吧),所以总体来看归并排序是稳定的排序算法。