欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C++堆排序算法實例詳解

 更新時間:2017年08月15日 11:14:00   作者:葉赫那拉坤  
這篇文章主要介紹了C++堆排序算法,簡單分析了堆排序算法的原理并結(jié)合實例形式分析了C++實現(xiàn)堆排序的具體操作技巧,需要的朋友可以參考下

本文實例講述了C++堆排序算法。分享給大家供大家參考,具體如下:

堆中元素的排列方式分為兩種:max-heap或min-heap,前者每個節(jié)點的key都大于等于孩子節(jié)點的key,后者每個節(jié)點的key都小于等于孩子節(jié)點的key。

由于堆可以看成一個完全二叉樹,可以使用連續(xù)空間的array來模擬完全二叉樹,簡單原始的實現(xiàn)如下:

#include<iostream>
int heapsize=0;//全局變量記錄堆的大小
void heapSort(int array[],int n){
 void buildHeap(int [],int);
 void exchange(int[],int,int);
 void heapify(int[],int);
 buildHeap(array,n);
 for(int i=n-1;i>=1;i--){
  exchange(array,0,i);
  heapsize--;
  heapify(array,0);
 }
}
//構建堆
void buildHeap(int array[],int n){
 void heapify(int[],int);
 heapsize=n;
 //從最小的父節(jié)點開始,進行堆化,直到樹根節(jié)點
 for(int i=heapsize/2-1;i>=0;i--){
  heapify(array,i);
 }
}
//堆化
void heapify(int array[],int n){
 void exchange(int[],int,int);
 int left_child=n*2+1;
 int right_child=n*2+2;
 int largest;
 if(left_child<heapsize&&array[left_child]>array[n]){
  largest = left_child;
 }
 else{
  largest = n;
 }
 if(right_child<heapsize&&array[right_child]>array[largest]){
  largest=right_child;
 }
 if(largest!=n){
  exchange(array,largest,n);
  heapify(array,largest);
 }
}
void exchange(int array[],int i,int j){
 int tmp = array[i];
 array[i]=array[j];
 array[j]=tmp;
}
int main(){
  int arr[9]={3,1,6,9,8,2,4,7,5};
  heapSort(arr,9);
  for(int i=0;i<9;++i){
    std::cout<<arr[i]<<" ";
  }
  std::cout<<std::endl;
  return 0;
}
STL中實現(xiàn)了max-heap的操作。在使用heap算法是需添加頭文件algorithm。
#include <iostream>
#include<vector>
#include<algorithm>
int main()
{
  int arr[9]={0,1,2,3,4,8,9,3,5};
  std::vector<int> vec(arr,arr+9);
  //0 1 2 3 4 8 9 3 5
  for(auto c:vec){
    std::cout<<c<<" ";
  }
  std::cout<<std::endl;
  make_heap(vec.begin(),vec.end());
  //9 5 8 3 4 0 2 3 1
  for(auto c:vec){
    std::cout<<c<<" ";
  }
  std::cout<<std::endl;
  vec.push_back(7);
  push_heap(vec.begin(),vec.end());
  //9 7 8 3 5 0 2 3 1 4
  for(auto c:vec){
    std::cout<<c<<" ";
  }
  std::cout<<std::endl;
  pop_heap(vec.begin(),vec.end());
  //8 7 4 3 5 0 2 3 1 9,只是將最大值挪到了vector的最后,并沒有刪除
  for(auto c:vec){
    std::cout<<c<<" ";
  }
  std::cout<<std::endl;
  std::cout<<vec.back()<<std::endl;//9
  //將9刪除
  vec.pop_back();
  //連續(xù)的pop_heap操作,每次的最大值都放在最尾端,最后呈現(xiàn)遞增排序
  sort_heap(vec.begin(),vec.end());
  //0 1 2 3 3 4 5 7 8
  for(auto c:vec){
    std::cout<<c<<" ";
  }
  std::cout<<std::endl;
  return 0;
}

希望本文所述對大家C++程序設計有所幫助。

相關文章

最新評論