堆排序(C語言)

來源:互聯網
上載者:User

標籤:

 
  1. #ifndef HEAP_SORT_H
  2. #define HEAP_SROT_H
  3. #include<iostream>
  4. void maxHeap(int *arr,unsigned int Length);
  5. void maxHeap(int *arr,unsigned int rootIndex,unsigned int heapSize);
  6. void builMaxHeap( int *arr,unsigned int heapSize);
  7. inline unsigned int right(unsigned int index);
  8. inline unsigned int left(unsigned int index);
  9. void heapSort(int *arr,int Length);
  10. inline unsigned int left(unsigned int index){
  11. return 2*index+1;
  12. }
  13. inline unsigned int right(unsigned int index){
  14. return 2*index+2;
  15. }
  16. void maxHeap(int *arr,unsigned int rootIndex,unsigned int heapSize){
  17. unsigned int leftIndex=left(rootIndex);
  18. unsigned int rightIndex=right(rootIndex);
  19. unsigned int largest;
  20. if(arr[leftIndex]>arr[rootIndex]&&leftIndex<heapSize){
  21. largest=leftIndex;
  22. }else{
  23. largest=rootIndex;
  24. }
  25. if(arr[rightIndex]>arr[largest]&&rightIndex<heapSize){
  26. largest=rightIndex;
  27. }
  28. if(largest!=rootIndex){
  29. int temp=arr[largest];
  30. arr[largest]=arr[rootIndex];
  31. arr[rootIndex]=temp;
  32. maxHeap(arr,largest,heapSize);
  33. }
  34. }
  35. void builMaxHeap( int *arr,unsigned int heapSize){
  36. for(int i=heapSize/2-1; i>=0;--i){
  37. maxHeap(arr,i,heapSize);
  38. }
  39. }
  40. void heapSort(int *arr,int Length){
  41. for(int size=Length-1;size>0;size--){
  42. builMaxHeap(arr,size);
  43. int temp=arr[size];
  44. arr[size]=arr[0];
  45. arr[0]=temp;
  46. }
  47. }
  48. #endif





來自為知筆記(Wiz)

堆排序(C語言)

聯繫我們

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