|
|
|
|
#include<iostream>
|
|
|
|
|
#define ElemType int
|
|
|
|
|
using namespace std;
|
|
|
|
|
void print(int a[], int n) {
|
|
|
|
|
for (int j = 0; j < n; j++) {
|
|
|
|
|
cout << a[j] << " ";
|
|
|
|
|
}
|
|
|
|
|
cout << endl;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
//<2F><>r[i<><69>m]<5D><>r[m +1 <20><>n]<5D>鲢<EFBFBD><E9B2A2><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>rf[i<><69>n]
|
|
|
|
|
void Merge(ElemType *r, ElemType *rf, int i, int m, int n)
|
|
|
|
|
{
|
|
|
|
|
int j, k;
|
|
|
|
|
for (j = m + 1, k = i; i <= m && j <= n; ++k) {
|
|
|
|
|
if (r[j] < r[i]) rf[k] = r[j++];
|
|
|
|
|
else rf[k] = r[i++];
|
|
|
|
|
}
|
|
|
|
|
while (i <= m) rf[k++] = r[i++];
|
|
|
|
|
while (j <= n) rf[k++] = r[j++];
|
|
|
|
|
print(rf, n + 1);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void MergeSort(ElemType *r, ElemType *rf, int lenght)
|
|
|
|
|
{
|
|
|
|
|
int len = 1;
|
|
|
|
|
ElemType *q = r;
|
|
|
|
|
ElemType *tmp;
|
|
|
|
|
while (len < lenght) {
|
|
|
|
|
int s = len;
|
|
|
|
|
len = 2 * s;
|
|
|
|
|
int i = 0;
|
|
|
|
|
while (i + len < lenght) {
|
|
|
|
|
Merge(q, rf, i, i + s - 1, i + len - 1); //<2F>Եȳ<D4B5><C8B3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ӱ<EFBFBD><D3B1>ϲ<EFBFBD>
|
|
|
|
|
i = i + len;
|
|
|
|
|
}
|
|
|
|
|
if (i + s < lenght) {
|
|
|
|
|
Merge(q, rf, i, i + s - 1, lenght - 1); //<2F>Բ<EFBFBD><D4B2>ȳ<EFBFBD><C8B3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ӱ<EFBFBD><D3B1>ϲ<EFBFBD>
|
|
|
|
|
}
|
|
|
|
|
tmp = q; q = rf; rf = tmp; //<2F><><EFBFBD><EFBFBD>q,rf<72><66><EFBFBD>Ա<EFBFBD>֤<EFBFBD><D6A4>һ<EFBFBD>˹鲢ʱ<E9B2A2><CAB1><EFBFBD>Դ<EFBFBD>q <20>鲢<EFBFBD><E9B2A2>rf
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
int main() {
|
|
|
|
|
int a[10] = { 3,1,5,7,2,4,9,6,10,8 };
|
|
|
|
|
int b[10];
|
|
|
|
|
MergeSort(a, b, 10);
|
|
|
|
|
print(b, 10);
|
|
|
|
|
cout << "<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>";
|
|
|
|
|
print(a, 10);
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
时间复杂度 O(N*logN)
|
|
|
|
|
归并排序的空间复杂度是O(n)
|