思路为:首先实现间隔1,2,4,8,16,,,(即每一层)的循环,然后,在这里边的每个循环里边,进行归并处理
#include<bits/stdc++.h>
using namespace std;
void Print_arr(int *p, int len)
{
for (int i = 0; i < len; i++)
cout << p[i] << " ";
cout << endl;
}
void paixu(int *s, int i, int mid, int n)
{
int *d = (int *)malloc((n - i + 1) * sizeof(int));
int x, y;
int l = 0;
for (x=i,y=mid;x<mid && y<=n;l++)
{
if (s[x] < s[y])
d[l] = s[x++];
else
d[l] = s[y++];
}
if (x < mid)
{
while (x < mid)
{
d[l++] = s[x++];
}
}
if (y <= n)
{
while (y <= n)
{
d[l++] = s[y++];
}
}
memcpy(s + i, d, (n-i+1)*sizeof(int));
free(d);
}
void Merge(int *s,int k,int n)
{
int i = 0;
while (i <= n + 1 - 2 * k) //把后面一个或者两个序列暂时先不管,因为他们得先判断才能进行归并
{
paixu(s, i, i + k, i + 2 * k - 1);
i += 2 * k;
}
if (i <= n - k)
{
paixu(s, i, i + k, n);
}
}
void MergeSort(int *s,int i,int n)
{
int k = 1;
while (k < n + 1)
{
Merge(s, k, n);
k *= 2;
}
}
int main()
{
int a[] = { 50,10,90,30,70,40,80,60,20 };
int dst[9];
MergeSort(a, 0, 8);
cout << "rel:" << endl;
Print_arr(a, sizeof(dst) / sizeof(int));
system("pause");
return 0;
}