前面写过选择排序和插入排序,下面是归并排序,如下:
#include<iostream>
using namespace std;
const int sentry = 999999;
void Merge( int ia[], size_t p, size_t q, size_t r)
{
int a1[10], a2[10];
size_t len1 = q - p + 1,len2=r-q;
for (int i = 0; i <len1; ++i)
a1[i] = ia[p+i];
a1[len1] = sentry;
for (int i = 0; i <len2; ++i)
a2[i] = ia[q+i+1];
a2[len2] = sentry;
int b = 0, c = 0;
for (int i = p; i <= r; ++i)
{
if (a1[b] >= a2[c])
ia[i] = a2[c++];
else
ia[i] = a1[b++];
}
}
void Merge_sort( int ia[],size_t p,size_t r)
{
if (p < r )
{
int q = (p + r) / 2;
Merge_sort(ia, p, q);
Merge_sort(ia, q + 1, r);
Merge(ia, p, q, r);
}
}
int main()
{
int a[20];
int n;
cout << "input the size of array:" << endl;
cin >> n;
for (int i = 0; i < n; ++i)
cin >> a[i]; //input array
Merge_sort(a, 0, n-1);
for (int i = 0; i < n; ++i)
cout << a[i] << " ";
cout << endl;
return 0;
}
写了一下午终于完工。