将琴存诗
人生 可以不要那么 耀 ,只需要有 一个  平凡的梦想  足以 。—— loveincode -_^ RSS
Fork me on GitHub

BottomupSort算法 c++代码实现

#include <iostream>
using namespace std;

#define N 100

int A[N];     
static int n;   


void Initial()
{
    cout << "请输入元素的个数:";
    cin >> n;
    cout << "请输入" << n << "个元素:";
    for(int i = 1; i <=n; i ++)
    {
        cin >> A[i];
    }
}

void Print()
{
    cout << "经过Bottomupsort后:";
    for(int i = 1; i <=n; i ++)
    {
        cout << A[i] << " ";
    }
    cout << endl;
}


void Merge(int a[], int p, int q, int r)
{
    int b[N];
    int s = p, t = q+1, k = p;
    
    while(s <= q && t <= r)
    {
        if(a[s] <= a[t])
        {
            b[k++] = a[s++];
        }
        else
        {
            b[k++] = a[t++];
        }
    }

    if(s==q+1)
    {
        for(int i = t; i <= r; i ++)
        {
            b[k++] = a[i];
        }
    }
    else
    {
        for(int j = s; j <= q; j ++)
        {
            b[k++] = a[j];
        }
    }

    //把b[]中排好的元素copy到a[]中
    for(int i = p; i <= r; i++)
    {
        a[i] = b[i];
    }
}


void Bottomupsort(int a[],int n)
{

   int t = 1;
   int s,i;
   while (t<n)
   {
        s = t;t =2*s;i=0;
        while(i+t<=n)
        {
            Merge(a,i+1,i+s,i+t);
            i = i+t;
        }
        if(i+s<n)
        {
            Merge(a,i+1,i+s,n);
        }
   }
}


int main()
{
    Initial();

    if(n > 1)
    {
        Bottomupsort(A,n);
        Print();
    }
    else if(n == 1)
    {
        Print();
    }
    system("pause");
    return 0;
}

 

posted @ 2015-05-12 10:33  loveincode  阅读(1113)  评论(0编辑  收藏  举报
最简单即最美
有了信仰,自己要坚持努力 2017.07.09 21:34