日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

排序算法之(7)——堆排序

發布時間:2023/12/1 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 排序算法之(7)——堆排序 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

【堆排序的思路】

堆排序主要是利用了堆的性質。對于大頂堆:堆中的每一個節點的值都不小于它的孩子節點的值,具體可參考我的還有一篇博客http://blog.csdn.net/adminabcd/article/details/46880591,那么大頂堆的堆頂元素就是當前堆中全部元素中最大的。


利用這個性質。進行例如以下操作,則能夠得到一個有序序列:

  • 將待排序的n個元素一個一個插入堆中,那么此時堆頂元素就是全部元素中最大的
  • 將堆頂元素取出,剩下的n-1個元素組成新的堆,新堆的堆頂元素是當前堆中元素中最大的,也就是全部元素中第二大的。

  • 將堆頂元素取出。剩下的n-2個元素組成新的堆,新堆的堆頂元素是當前堆中元素中最大的。也就是全部元素中第三大的。
    .
    .
    .
    .

  • 直到全部元素取出,此時全部取出元素序列就是一個從大到小的有序序列。

  • 【代碼實現】

  • 大頂堆的實現
  • #ifndef maxheap_h #define maxheap_h template<class T> class Maxheap { public:Maxheap(int size);~Maxheap();bool Isempty();void push(T item); //插入操作void pop(); //刪除操作T top(); private:T *heap;int currentSize;int capacity; }; //-------構造函數初始化------- template<class T> Maxheap<T>::Maxheap(int size) {if(size<1){throw"capacity must be >=1";}else{currentSize=0;capacity=size;heap=new T[capacity+1]; //heap[0]不使用} } //-------析構函數釋放空間------- template<class T> Maxheap<T>::~Maxheap() {delete []heap; } //--------推斷堆是否為空------- template<class T> bool Maxheap<T>::Isempty() {return currentSize==0; } //---------獲取最大元素---------- template<class T> T Maxheap<T>::top() {return heap[1]; } //-------插入操作----- template<class T> void Maxheap<T>::push(T item) {if(currentSize==capacity)throw"Maxheap is full";else{currentSize++;int currentNode=currentSize;// 元素的插入位置初始化為最后while(currentNode>1&&heap[currentNode/2]<item) //(從下往上)進行調整{heap[currentNode]=heap[currentNode/2];currentNode=currentNode/2;}heap[currentNode]=item; //插入元素} }//-----刪除操作------- template<class T> void Maxheap<T>::pop() {if(Isempty())throw"heap is empty ,cannot delete";else{T last=heap[currentSize]; //將最后一個元素初始化為根currentSize--;int currentNode=1; int child=2;while(child<=currentSize) //(從上往下)進行調整{if(child<currentSize&&heap[child]<heap[child+1])child++;if(last>=heap[child])break;else{heap[currentNode]=heap[child];currentNode=child;child=child*2;}}heap[ currentNode]=last; } } #endif
  • 堆排序實現
  • #include"MAXHEAP.h" #include<iostream> using namespace std; int main() {Maxheap<int> H(100);int arr[]={50,15,30,70,6};for(int i=0;i<5;i++){H.push(arr[i]); //元素進堆}for(int i=0;i<5;i++){arr[i]= H.top();H.pop(); //取出堆頂元素。其余元素組成新的堆}cout<<"降序排序:";for(int i=0;i<5;i++){cout<<arr[i]<<" ";}cout<<endl;cout<<"升序排序:";for(int i=4;i>=0;i--){cout<<arr[i]<<" ";}cout<<endl;system("pause");return 0; }

    【結果】

    轉載于:https://www.cnblogs.com/claireyuancy/p/7131905.html

    總結

    以上是生活随笔為你收集整理的排序算法之(7)——堆排序的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。