第九章中位元和順序統計學之“尋找第i小的元素(遞迴版)平均已耗用時間為O(n)演算法”

來源:互聯網
上載者:User

類似於快速排序的隨機化版本,但是這裡每次只處理劃分的一側。最壞情況下時間複雜度為O(n^2),即每次都是按最大區間進行劃分。但在平均情況下,任何順序統計量(特別是中位元)都可以線上性時間內得到,時間複雜度為O(n)。

#include <string.h>#include <time.h>#define BUFFER_SIZE 10int RandomizedPartition(int *a,int p,int r){int i=0;int j=0;int tmp=0;int x=0;srand((unsigned)time(NULL));i=rand()%(r-p+1)+p;tmp=a[i];a[i]=a[r];a[r]=tmp;x=a[r];i=p-1;for(j=p;j<r;j++){if(a[j]<=x){i++;tmp=a[i];a[i]=a[j];a[j]=tmp;}}i++;tmp=a[i];a[i]=a[r];a[r]=tmp;return i;}int RandomizedSelect(int *a,int p,int r,int i){int q=0;int k=0;if(p==r){return a[p];}q=RandomizedPartition(a,p,r);k=q-p+1;if(k==i){return a[q];}else if(i<k){return RandomizedSelect(a,p,q-1,i);}else{return RandomizedSelect(a,q+1,r,i-k);}}int main(){int i=0;int j=0;int a[BUFFER_SIZE];printf("隨機產生的數組:\n");srand((unsigned)time(NULL));for(i=0;i<BUFFER_SIZE;i++){a[i]=rand()%100;//歸一化 printf("%d  ",a[i]);}printf("\n");i=BUFFER_SIZE/2;j=RandomizedSelect(a,0,BUFFER_SIZE-1,i);printf("第i=%d小的元素是:%d\n",i,j); system("pause");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.