演算法導論第9章(o(3n/2)時間內找出最大最小值)

來源:互聯網
上載者:User
#include <iostream.h>#include <limits.h>   //包含INT_MAX,INT_MIN的標頭檔 int nMax = INT_MIN;   //將INT_MIN設為當前最大值的初始值int nMin = INT_MAX;/////記錄比較最大值函數void Max(int& nNum){ nMax = nNum > nMax ? nNum : nMax ;}/////記錄比較最小值函數void Min(int& nNum){nMin = nMin < nNum ? nMin : nNum;   }void Max_Min(int nData[],int nLen){if (nLen%2 == 1)   //待測資料為奇數    {        //待測資料為奇數,最值初始值均設為nData[0]        Max(nData[0]);          Min(nData[0]);        for (int i=1;i<=(nLen-1)/2;i++)        {            if (nData[i]>nData[nLen-i])            {                Max(nData[i]);                Min(nData[nLen-i]);            }             else            {                Max(nData[nLen-i]);                Min(nData[i]);            }        }    }     else               //待測序列為偶數    {        for (int i=0;i<nLen/2;i++)        {            if (nData[i]>nData[nLen-i-1])            {                Max(nData[i]);                Min(nData[nLen-i-1]);            }             else            {                Max(nData[nLen-i-1]);                Min(nData[i]);            }        }    }}void main(){    //測試序列    int nData[] = {3,2,5,9,5,2,1,13,0,-1,43};    int nLen = sizeof(nData)/sizeof(nData[0]);Max_Min(nData,nLen);        cout<<"nMax = "<<nMax<<endl<<"nMin = "<<nMin<<endl;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.