冒泡排序

for 没优化 On²n²n²

int main
{
    int n = 10;
    int a151515 = {0,10,9,8,7,6,5,4,3,2,1};
    forinti=1;i<n;i++int i = 1 ; i < n ; i ++inti=1;i<n;i++
    {
        forintj=1;j<n;j++int j = 1 ; j < n ; j ++intj=1;j<n;j++
        {
            ifajjj>aj+1j+1j+1ajjj > aj+1j + 1j+1ajjj>aj+1j+1j+1
            { 
                swapajjj,aj+1j+1j+1ajjj , aj+1j + 1j+1ajjj,aj+1j+1j+1;
            }
        }
    }
    for inti=1;i<=n;i++int i = 1; i <= n ; i ++inti=1;i<=n;i++
    {
        cout << aiii << ' ';
    }
    return 0;
}

优化后for 最优条件下最优条件下最优条件下Onnn

int main
{
    int n = 10;
    int a151515 = {0,10,9,8,7,6,5,4,3,2,1};
    forinti=1;i<n;i++int i = 1 ; i < n ; i ++inti=1;i<n;i++
    {
        bool b = true;
        for(int j = 1 ; j < n ; j ++)
        {
            if(a[j] > a[j + 1])
            { 
                swap(a[j] , a[j + 1]);
                b = false;
            }
        }
        if(b) break;
    }
    for (int i = 1; i <= n ; i ++)
    {
        cout << a[i] << ' ';
    }
    return 0;
}

优化后 while 最优情况下 O(n)

int main()
{
    int n = 10;
    int a[15] = {0,10,9,8,7,6,5,4,3,2,1};
    bool b;
    do
    {
        b = false;
        for(int j = 1 ; j < n ; j ++)
        {
            if(a[j] > a[j + 1])
            { 
                swap(a[j] , a[j + 1]);
                b = true;
            }
        }
    }
    while(b);
    
    for (int i = 1; i <= n ; i ++)
    {
        cout << a[i] << ' ';
    }
    return 0;
}