zoukankan      html  css  js  c++  java
  • 各种排序总结(四)冒泡排序

    思想:

    一共n-2次外循环,每次循环将最大的数放到未排序的数列的最后。

    #include <iostream>
    
    using namespace std;
    void BubbleSort(int* arr, int n)
    {
        bool Swap;
        int i,j;
        for(i=0; i<n-1; i++)
        {
            Swap = false;
            for(j=0; j<n-i-1; j++)
            {
                if(arr[j] > arr[j+1])  //较大的放到后面
                {
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                    Swap = true;
                }
            }
            if(!Swap)  //没有发生交换
             return;
        }
    }
    int main()
    {
        int * arr;
        int n;
        cout<<"Input the arr length:"<<endl;
        cin>>n;
        arr = new int[n];
        cout<<"Input the arr elements:"<<endl;
        for(int i=0;i<n;i++)
        {
            cin>>arr[i];
        }
        BubbleSort(arr,n);
        cout<<"The outcome:"<<endl;
        for(int i=0;i<n;i++)
            cout<<arr[i]<<endl;
        return 0;
    }
    /******************
    稳定
    最佳时间代价:输入数组为正序时,只运行第一轮循环进行n-2次比较后就发现没有交换,
                   结束排序,因此最小时间代价O(n)。
    最差时间代价:外层n-2次,内层n-i次,O(n^2)。
    平均时间代价:O(n^2)。
    空间复杂度:只用一个临时变量,O(1)。
    总结:
    1.由于平均时间为O(n^2),适用于n较小的情况。
    2.由于输入数组正序时O(n),因此适用于输入基本有序的情况。
    *******************/
  • 相关阅读:
    暑期测试训练3
    对于在线段树上修改整段区间的理解
    UVA 11090 判负圈问题
    ZOJ 2588 求割边问题
    POJ 1523 网络连通
    hdu 1163
    hdu 1703
    hdu 2577 模拟
    hdu 3836 强连通+缩点:加边构强连通
    hdu 2571
  • 原文地址:https://www.cnblogs.com/CnZyy/p/3314688.html
Copyright © 2011-2022 走看看