標籤:
#include <iostream>
using namespace std;
#define N 100
int g_array[N]; //存放輸入的數字
static int count; //存放元素的個數
// 初始化函數
void Initial()
{
cout << "請輸入元素的個數:";
cin >> count;
cout << "請輸入" << count << "個元素:";
for(int i = 0; i < count; i ++)
{
cin >> g_array[i];
}
}
//合并函數
void Merge(int a[], int l, int m, int r)
{
int i = l, j = m+1, k = l;
int b[N];
while(i <= m && j <= r)
{
if(a[i] <= a[j])
{
b[k++] = a[i++];
}
else
{
b[k++] = a[j++];
}
}
if(i > m)
{
for(int p = j; p <= r; p ++)
{
b[k++] = a[p];
}
}
else
{
for(int p = i; p <= m; p ++)
{
b[k++] = a[p];
}
}
//把b[]中排好的元素copy到a[]中
for(int q = l; q <= r; q ++)
{
a[q] = b[q];
}
}
// 歸併排序 遞迴演算法表示
void Bottomupsort(int a[], int left, int right)
{
if(left < right) //數組至少要有兩個元素
{
int i = (right + left)/2;
Bottomupsort(a, left, i);
Bottomupsort(a, i+1, right);
Merge(a, left, i, right); //把left到right的元素排序好
}
}
//列印排好序的數組
void Print()
{
cout << "經過Bottomupsort後:";
for(int i = 0; i < count; i ++)
{
cout << g_array[i] << " ";
}
cout << endl;
}
int main()
{
Initial();
if(count > 1)
{
Bottomupsort(g_array, 0, count-1);
Print();
}
else if(count == 1)
{
Print();
}
system("pause");
return 0;
}
演算法設計與分析 上機題Mergesort