期望為線性時間的選擇演算法RANDOM_SELECT

來源:互聯網
上載者:User

標籤:

 1 #include<iostream> 2 #include<ctime> 3 using namespace std; 4 void swap(int *a, int *b) 5 { 6     int *c = a; 7     a = b; 8     b = c; 9 }10 int Partition(int *A, int p, int r)// 劃分11 {12     int x = A[r];13     int i = p - 1;14     for (int j = p; j < r; j++)15     {16         if (A[j] < x)17         {18             i++;19             swap(A[i],A[j]);20         }21     }22     swap(A[i+1],A[r]);23     return (i+1);24 }25 int Rand(int M, int N)//實現區間為[M,N]的隨機數26 {27     return (int)((double)rand() / (double)RAND_MAX*(N - M + 1) + M);28 }29 int Randmom_Partion(int *A, int p, int r)//劃分的隨機版本30 {31     int x = Rand(p,r);32     swap(A[r],A[x]);33     return Partition(A, p, r);34 }35 int Random_Select(int *A, int p, int r, int i)//隨機播放36 {37     if (p == r)38         return A[p];39     int q = Randmom_Partion(A,p,r);40     int k = q - p + 1;41     if (k == i)42         return A[q];43     else if (i < k)44         return Random_Select(A, p, q - 1, i);45     else46         return Random_Select(A, q + 1,r, i - k);//當在右側時,注意修改下一次i值47 48 }49 int main()50 {51     int A[] = {2,4,1,3,5,100,6,6,2,102};52     int N = sizeof A / sizeof A[0];53     srand((int)time(0));//必須放在調用前,不可放到產生隨機數的函數中54     cout << Random_Select(A,0,N-1,8)<<endl;55 56 }

 

期望為線性時間的選擇演算法RANDOM_SELECT

聯繫我們

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