归并排序
Posted vito_wang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了归并排序相关的知识,希望对你有一定的参考价值。
归并排序
归并的排序的核心在于合并,递归到底一个数字自然有序
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;
}
算法分析
合并的时间复杂度为 \(\theta(n)\)
归并时间复杂度 \(T(n)=\begin{cases} \theta(1) & n=1 \\ 2T(n/2) + \theta(n) & n>1 \end{cases}\)
通过求解递归树,每一层为\(cn\), 共\(nlgn+1\)层,故时间复杂度为\(\theta(nlgn)\)
在30个元素以上,归并排序由于插入排序`
以上是关于归并排序的主要内容,如果未能解决你的问题,请参考以下文章