資料結構、演算法與應用 (C++描述) 第二版 1.6__python

來源:互聯網
上載者:User
這個寫了蠻長時間的,主要是在想如何讓程式判斷不是一種排序後檢查是不是另一種排序,我想出的這個方法可能不是最優的,如果誰有更好的辦法,請留言告訴我。**僅給有需要的人以參考,如有錯誤請糾正我**
#include<iostream>template<typename T>bool is_sorted(T arr[], int n){    T temp;    int i;    for (i = 0; i < n; i++)             //首先檢測降序    {        temp = arr[i];        if (i == n - 2)                 //如果檢測到了倒數第二個數 則它大於或等於最後一個數就返回ture        {                               //如果不滿足>=  那就再檢測是否是升序排序            if (temp >= arr[i + 1])                     return true;            else                 break;        }        if (temp > arr[i + 1])          //因為倒數第二個數之前的數用這個檢測了,如果有錯誤 就退出迴圈 檢測升序            continue;    }    for (i = 0; i < n; i++)             //檢測升序    {        temp = arr[i];        if (i + 1 == n)                 //這是為了防止temp == arr[n - 1] 與 arr[n] 做比較 因為超出數組邊界了            break;                      //會返回一個很大的負數        if (temp <= arr[i + 1])            continue;        else             return false;    }    return true;}int main(){    using namespace std;    int arr[5] = { 20, 20, 30, 50, 60 };    if (is_sorted(arr, 5))        cout << "true\n";    else        cout << "false\n";    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.