冒泡排序

来源:互联网 发布:网络教育网 编辑:程序博客网 时间:2024/06/05 15:47

冒泡排序
在一次冒泡过程中,相邻的元素比较,如果左边的元素大于右边的元素,则交换。一次冒泡过程结束后,最大的元素肯定在最右端。然后进行其他的冒泡过程。

template<class T>bool bubble(T a[], int n){    // 把数组a[0:n-1]中的最大元素移到最右端    // 目前为止未交换    bool swapped = false;     for(int i = 0; i < n-1; i++)    {        if(a[i] > a[i+1])        {            // 交换            T temp = a[i];            a[i] = a[i+1];            a[i+1] = temp;            swapped = true;        }    }    return swapped;}template<class T>void bubbleSort(T a[], int n){    // 及时终止的冒泡排序    for(int i = n; i > 1 && bubble(a, i); i--);}
0 0