堆排序及top K 演算法__演算法

來源:互聯網
上載者:User
static void swap(int* left,int *right){int tmp=*left;*left=*right;*right=tmp;}void adjustdown(int* arr,int i,int end){int key=arr[i];int p=i;int left=2*p+1;while(left<=end){if(key>arr[left]&&(left+1<=end)&&key>arr[left+1]){break;}else if(key>arr[left]&&left+1>end){break;}else if(left+1<=end&&arr[left+1]>=arr[left]&&key<arr[left+1]){swap(arr+p,arr+left+1);p=left+1;left=2*p+1;}else if(left+1<=end&&arr[left]>arr[left+1]&&key<arr[left]){swap(arr+p,arr+left);p=left;left=2*p+1;}else if(left+1>end&&arr[left]>key){swap(arr+p,arr+left);p=left;left=2*p+1;}else{break;}}}void heap_sort(int* arr,int len){int p;int end;for(p=(len-2)/2;p>=0;p--){adjustdown(arr,p,len-1);//len是數組長度}for(end=len-1;end>=1;end--){swap(arr,arr+end);adjustdown(arr,0,end-1);}}void my_top(int* arr,int len,int top,int* arr_top,int top_len){int index;for(index=0;index<len;index++){if(index<top){if(index==0){arr_top[index]=arr[index];}else{int pos;for(pos=index-1;pos>=0;pos--){if(arr[index]>=arr_top[pos]){arr_top[pos+1]=arr_top[pos];}else{break;}}arr_top[pos+1]=arr[index];}}else{if(arr[index]>arr_top[0]){continue;}else{arr_top[0]=arr[index];adjustdown(arr_top,0,top_len-1);}}}}

聯繫我們

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