堆排序(C++实现)
#include<iostream> #include<vector> using namespace std; void swap(vector<int> &arr, int a, int b) { int temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } void ajust_heap(vector<int>&arr, int hole, int len) { int Rchild; Rchild = 2*hole+2; while(Rchild<len) { if(arr[Rchild]<arr[Rchild-1]) Rchild--; if(arr[Rchild]>arr[hole]) {swap(arr, Rchild, hole); hole = Rchild; Rchild = 2*hole+2;} else break; } if(Rchild==len&&arr[Rchild-1]>arr[hole]) swap(arr, hole, Rchild-1); } void build_heap(vector<int> &arr) { int size = arr.size(); for(int hole=size/2-1; hole>=0; hole--) { ajust_heap(arr, hole, size); } } void heapSort(vector<int>& arr) { int len = arr.size(); for(int i=len-1; i>=0; i--) { cout<<arr[0]<<" "; arr[0] = arr[i]; ajust_heap(arr, 0, i); } } int main() { int a[] = {2,1,4,6,7,6,5,3,3,4,8}; vector<int> arr(a, a+sizeof(a)/sizeof(int)); build_heap(arr); heapSort(arr); return 0; }