hihocoder#1128之非有序數組二分尋找

來源:互聯網
上載者:User
提示二:非有序數組的二分尋找 輸入

第1行:2個整數N,K。N表示數組長度,K表示需要尋找的數 輸出

第1行:一個整數t,表示K在數組中是第t小的數,若K不在數組中,輸出-1

第2行:N個整數,表示a[1..N],保證不會出現重複的數,1≤a[i]≤2,000,000,000 範例輸入

10 51802970 663 5480 4192 4949 1 1387 4428 5180 2761
範例輸出
9
#include#includeusing namespace std;#define swap(x, t, y) (t = x, x = y, y = t)//交換x和yint a[1111111], k;int find(int s, int e)//快排思想{if(s == e && a[s] != k)return -1;int i = s - 1, j, t, r, x = a[e];for(j = s; j < e; j++){if(a[j] <= x){i++;swap(a[i], t, a[j]);}}swap(a[i + 1], t, a[e]);if(a[i + 1] < k){r = rand()%(e - i - 1) + i + 2;//隨機播放a[r]作為主元swap(a[r], t, a[e]);find(i + 2, e);}else if(a[i + 1] > k){r = rand()%(i + 1 - s) + s;swap(a[r], t, a[i]);find(s, i);}elsereturn i + 1;}int main(void){int i, n, r, t;cin>>n>>k;for(i = 1; i <= n; i++)cin>>a[i];r = rand()%n + 1;swap(a[r], t, a[n]);cout<


聯繫我們

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