这个不知有什么可以优化的。
#include <stdio.h>
struct interval {
int l , r;
interval() {}
interval(int _l , int _r):l(_l) , r(_r) {}
};
typedef interval data;
const int MaxN = 1000;
int a[MaxN] , b[MaxN];
class Stack
{
public:
Stack(){top = 0;}
data pop() {
return s[-- top];
}
void push(data now) {
s[top ++] = now;
}
data _top() {
return s[top - 1];
}
bool empty() {
return top == 0;
}
private:
data s[MaxN];
int top;
};
void Merge(int *a , data p)
{
int i , j;
int p1 = p.l , mid = (p.l + p.r) >> 1 , p2 = mid + 1;
for (i = p.l;i <= p.r && p1 <= mid && p2 <= p.r;i ++) {
if (a[p1] > a[p2]) b[i] = a[p2 ++];
else b[i] = a[p1 ++];
}
while (p1 <= mid) b[i ++] = a[p1 ++];
while (p2 <= p.r) b[i ++] = a[p2 ++];
for (i = p.l;i <= p.r;i ++) {
a[i] = b[i];
}
}
//非递归归并排序(那应该不叫“归并”了吧。。)
void Sort(int *a , int n)
{
data now(0 , n - 1);
Stack St;
if (now.l >= now.r) return;
St.push(now);
while (now.l != now.r) {
St.push(interval(now.l , now.r = ((now.l + now.r) >> 1)));
}
while (!St.empty()) {
now = St.pop();
while (!St.empty() && now.r == St._top().r) {
now = St.pop();
Merge(a , now);
}
if (!St.empty()) {
now = St._top();
now = interval(1 + ((now.l + now.r) >> 1) , now.r);
St.push(now);
while (now.l != now.r) {
St.push(interval(now.l , now.r = ((now.l + now.r) >> 1)));
}
}
}
}
void __test()
{
int n , i;
scanf("%d" , &n);
for (i = 0;i < n;i ++) {
scanf("%d" , &a[i]);
}
Sort(a , n);
puts("归并后的序列:");
for (i = 0;i < n;i ++) {
printf("%d " , a[i]);
}
puts("");
}
int main()
{
__test();
}
/*
9
3 2 3 77 8 999 10 4 3
10
7 8 77 8 6 4 3 3 2 33
*/