冒泡排序 C++版

版权声明:本文为博主原创文章,转载请注明出处。作者:ISmileLi 博客地址:http://blog.csdn.net/toby54king。 https://blog.csdn.net/toby54king/article/details/83689160

一、说明:冒泡排序的原理在注释中,文中冒泡排序使用了模板来传入数据,详细情况看下面的测试代码。

二、测试代码

    #include <iostream>
    #include <vector>
    
    using namespace std;
    /******************************
    冒泡排序:从数组的右到左对数组进行两两比较排序,大的放到最右边。
    第一遍比较后最小的元素在最左边的0号位置,第二遍开始将第2小的数
    据放到1号位置,一直比较到只剩最后两个元素确认是否交换为止。
    优点:1、简单
    缺点:1、在各种情况下的比较次数都相等,效率低
    算法复杂度:O(n~n^2) 空间复杂度:O(1)
    ******************************/
    
    // 实现方法一
    template<typename T>
    void bubbleSort1(T data[], int n)
    {
        for(int i=0; i<n-1; i++)
        {
            for(int j=n-1; j>i; j--)
            {
                if(data[j]<data[j-1])
                {
                    T temp = data[j];
                    data[j] = data[j-1];
                    data[j-1] = temp;
                }
            }
        }
    }
    
    // 实现方法二冒泡改进版
    template<typename T>
    void bubbleSort2(T data[], int n)
    {
        // 设置标志位用来查看是否发生交换,如果没有发生交换说明排序已经完成,不需要再进行排序
        // 这种情况发生的概率不多,这种改进需要额外保存一个变量,效果可能还不如第一种效果好
        bool flag = true;
        for(int i=0; i<n-1 && flag; i++)
        {
            flag = false;
            for(int j=n-1; j>i; j--)
            {
                if(data[j]<data[j-1])
                {
                    T temp = data[j];
                    data[j] = data[j-1];
                    data[j-1] = temp;
                    flag = true;
                }
            }
        }
    }
    
    // 实现方法三
    template<typename T>
    void bubbleSort3(vector<T> &data)
    {
        for(int i=0; i<data.size()-1; i++)
        {
            for(int j=data.size()-1; j>i; j--)
            {
                if(data[j] < data[j-1])
                {
                    T temp = data[j];
                    data[j] = data[j-1];
                    data[j-1] = temp;
                }
            }
        }
    }
    
    int main()
    {
        int tempArr[] = {0,4,3,5,6,7,9,8,2,1};
        int arrSize = sizeof(tempArr)/sizeof(tempArr[0]);
        cout << "arrSize=" << arrSize << endl;
        // bubbleSort1 test
        // bubbleSort1(tempArr,arrSize);
        // bubbleSort2(tempArr,arrSize);
        vector<int> tempVec(tempArr,tempArr+arrSize);
        bubbleSort3(tempVec);
        cout << "===========bubbleSort tempArr==========" << endl;
        for(int i=0; i<arrSize; i++)
        {
            cout << tempArr[i] << endl;
        }
        cout << "===========bubbleSort tempVec==========" << endl;
        for(int i=0; i<arrSize; i++)
        {
            cout << tempVec[i] << endl;
        }
        cout << "Hello World!" << endl;
        return 0;
    }

三、测试结果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/toby54king/article/details/83689160