交换排序(冒泡法)

#include <iostream>
using namespace std;

void bubbleSort(int a[],int n)
{
    bool flag = true;

    for (int i = n - 1; flag && i > 0; i--)
    {
        flag = false;

        for (int j = 0; j < i; j++)
        {
            if (a[j] > a[j + 1])
            {
                int temp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = temp;

                flag = true;
            }
        }
    }
}

int main()
{
    int a[] = {9,3,2,5,6,4,8,1};

    int size = sizeof(a)/sizeof(int);

    for (int i = 0; i < size; ++i)
    {
        cout << a[i] << endl;
    }

    cout << endl;

    bubbleSort(a, size);

    for (int i = 0; i < size; ++i)
    {
        cout << a[i] << endl;
    }

}

 

posted @ 2013-01-10 17:55  rookieeeeee  阅读(236)  评论(0编辑  收藏  举报