• 1 冒泡排序


    1.冒泡排序 重复地走访过要排序的数列,一次比较两个相邻元素,时间复杂度最少为n-1 最坏为 n(n-1)/2 ,因此O(n^2)     因为是相邻两个相互比较因此 是稳定排序

    #include <iostream>
    using namespace std;
    //最经典的课本书上的排序, 将第i个跟后面所有的比较 然后将最小的放在i位上。严格意义上来说不是相邻两个相互比较
    void BubbleSort(int a[], int n) 
    {
        for(int i=0;i<n-1;i++)
        {
            for(int j=i+1;j<n;j++)
            {
                if(a[i]>a[j])
                {
                    int temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                }
            }
        }
    }
    // 从最底层开始 两两比较 将最小的放在最前面 正宗冒泡排序
    void BubbleSort1(int a[], int n)
    {
      int count1=0,count2=0;
        for(int i=0;i<n-1;i++)
        {
            count1++;
            for(int j=n-1; j>i; j--)
            {
                if(a[j-1]>a[j])
                {
                    count2++;
                    int temp = a[j-1];
                    a[j-1] = a[j];
                    a[j] = temp;
                }
            }
        }
        cout<<"count1="<<count1<<endl;
        cout<<"count2="<<count2<<endl;
    }
    // 如果第i 次经过排序后已经排好了 那么i+1到n-1次就不用比较了
    void BubbleSort11(int a[], int n)
    {
        bool flag = true;
        int count1=0,count2=0;
        for(int i=0;i<n-1 && flag;i++)
        {
            count1++;
            flag = false;
            for(int j=n-1; j>i; j--)
            {
                if(a[j-1]>a[j])
                {
                    count2++;
                    int temp = a[j-1];
                    a[j-1] = a[j];
                    a[j] = temp;
                    flag = true;
                }
            }
        }
        cout<<"count1="<<count1<<endl;
        cout<<"count2="<<count2<<endl;
    }
    // 自上而下对相邻的两个数依次进行比较和调整,每次最大数放在最底层
    void BubbleSort2(int a[], int n)
    {
        for(int i=0;i<n-1;i++)
        {
            for(int j=0;j<n-1-i;j++)
            {
                if(a[j]>a[j+1])
                {
                     int tmp = a[j]; a[j] = a[j+1];  a[j+1] = tmp;
                }
            }
        }
    }
    int main()
    {
        int a[9]={9,8,7,6,5,4,3,2,1};
        BubbleSort2(a,9);
        for(int i=0;i<9;i++)
        {
            cout<<a[i]<<" ";
        }
        cout<<endl;
        return 0;
    }


    关注公众号 海量干货等你
  • 相关阅读:
    Recyclerview设置间距
    Python-socket / socketserver
    服务器存储空间不足,无法处理此命令
    gitbucket
    一些好用的Linux命令组合
    Python socket模块
    用Python在局域网根据IP地址查找计算机名
    thinkpad开机引导方式变成PCI LAN选项解决
    ipython安装
    python xml
  • 原文地址:https://www.cnblogs.com/sowhat1412/p/12734491.html
Copyright © 2020-2023  润新知