堆排序

来源:互联网 发布:戎美质量 知乎 编辑:程序博客网 时间:2024/06/02 04:50

对于堆排序,有以下几点需要注意:

  1. 堆化操作。将数组堆化有两种方法:一种是依次插入数组中的元素,使其堆化,另一种是自底向上。由于我们知道全部的元素,此时选择自底向上的方法,其时间复杂度为O(n),插入法的时间复杂度为O(nlog(n))。
  2. 在堆化操作当中,核心部分是3个结点比大小,不断下塑,从而找到合适的位置存放违规的元素。
  3. 将堆有序化,方法是不断执行出堆操作。
附件:

void heap_shift_down(int *a, int hole, int size){int l = 2*hole + 1;int tmp = a[hole];while(l < size){if(l + 1 < size && a[l + 1] > a[l])l++;if(a[l] > a[hole]){a[hole] = a[l];hole = l;l = 2*hole + 1;}else{break;}}a[hole] = tmp;}void heap_sort(int *a, int size){//heapifyint parent = (size - 2)/2;while(parent >= 0)heap_shift_down(a, parent--, size);//pop upwhile(size--){swap(a[0], a[size]);heap_shift_down(a, 0, size);}}int g_a[] = {13, 12 , 5, 6, 0, 2};int main(){heap_sort(g_a, sizeof(g_a)/sizeof(int));return 0;}


原创粉丝点击