堆排序的实现
堆排序也是一种重要的排序方式,时间复杂度能达到O(nlogn),是非常优越的排序,下面给出具体代码,原理和思路还是google一下吧,我语言欠缺描述不好,很多大神的博客里都有详细的讲解。
#include<iostream> using namespace std; void max_heapify(int data[],int i,int heapsize) { int l,r; int largest = i; l = 2 * i + 1; r = 2 * i + 2; if(l < heapsize && data[l] > data[i]) largest = l; if(r < heapsize && data[r] > data[largest]) largest = r; if(largest != i) { int tmp = data[largest]; data[largest] = data[i]; data[i] = tmp; max_heapify(data,largest,heapsize); } } void set_max_heap(int data[],int heapsize) { for(int i = heapsize / 2 - 1;i >= 0;i --) max_heapify(data,i,heapsize); } void heap_sort(int data[],int heapsize) { set_max_heap(data,heapsize); for(int i = heapsize - 1;i > 0;i --) { int t = data[0]; data[0] = data[i]; data[i] = t; max_heapify(data,0,i); } } int main() { int data[10] = {3,6,1,9,4,5,2,7,0,8}; heap_sort(data,10); for(int i = 0;i < 10;i ++) cout<<data[i]<<" "; cout<<endl; }
输出结果: