归并排序
归并的排序的核心在于合并,递归到底一个数字自然有序
python
def merge(A, p, q, r):
L = A[p:q+1]
R = A[q+1:r+1]
L.append(float("inf"))
R.append(float("inf"))
i = 0
j = 0
k = p
while k <= r:
if L[i] <= R[j]:
A[k] = L[i]
i = i + 1
k = k + 1
else:
A[k] = R[j]
j = j + 1
k = k + 1
def merge_sort(A, p, r):
if p < r:
q = (p + r) // 2
merge_sort(A,p,q)
merge_sort(A,q+1,r)
merge(A,p,q,r)
if __name__ == "__main__":
A = [5, 2, 4, 7, 1, 3, 2, 6]
print("排序前", A)
merge_sort(A, 0, 7)
print("排序后", A)
c++
#include <iostream>
#include <limits.h>
using namespace std;
void merge(int A[], int p, int q, int r)
{
int n1 = q - p + 1;
int n2 = r - q;
int L[n1+1];
int R[n2+1];
L[n1] = INT_MAX;
R[n2] = INT_MAX;
for (int i = 0; i < n1; i++)
{
L[i] = A[p+i];
}
for (int i = 0; i < n2; i++)
{
R[i] = A[q+i+1];
}
int i = 0;
int j = 0;
for (int k = p; k <= r; k++)
{
if (L[i] <= R[j])
{
A[k] = L[i];
i = i + 1;
}
else
{
A[k] = R[j];
j = j + 1;
}
}
}
void merge_sort(int A[], int p, int r)
{
if (p < r)
{
int q = (p + r) / 2;
merge_sort(A, p, q);
merge_sort(A, q+1, r);
merge(A, p, q, r);
}
}
int main()
{
int A[] = {5, 2, 4, 7, 1, 3, 2, 6};
cout << "排序前 ";
for(int i = 0; i < 8; i++)
{
cout << A[i] << " ";
}
cout << endl;
merge_sort(A, 0, 7);
cout << "排序后 ";
for(int i = 0; i < 8; i++)
{
cout << A[i] << " ";
}
return 0;
}
算法分析
合并的时间复杂度为 $ heta(n)$
归并时间复杂度 $T(n)=egin{cases}
heta(1) & n=1
2T(n/2) + heta(n) & n>1
end{cases}$
通过求解递归树,每一层为$cn$, 共$nlgn+1$层,故时间复杂度为$ heta(nlgn)$
在30个元素以上,归并排序由于插入排序`