数据结构之堆(Heap)

青旅半醒 2024-04-17 19:40 162阅读 0赞

堆是由完全二叉树实现的
完全二叉树: 若设二叉树的深度为h,除第h层外,其他各层(1—h-1)的结点数都达到最大个数,第h层所有的结点都连续集中在最左边,这就是完全二叉树。

  1. left_son_id = father_id*2+1
  2. right_son_id = father_id*2+2

最大堆: 每个结点的键值(key)都大于等于子节点键值,最大堆的最大元素在根节点,位于array的头。
最小堆: 每个结点的键值(key)都小于等于子节点键值,最小堆的最小元素在根节点,位于array的头。
在这里插入图片描述

  1. public class Heap {
  2. //parent = (child-1)/2
  3. //c1 = 2p+1
  4. //c2 = 2p+2
  5. //n表示这个树有多少个节点
  6. //i表示要对哪个节点进行堆化
  7. public static void heapify(int[] tree,int n,int i){
  8. if (i>=n){
  9. return;
  10. }
  11. int c1 = 2*i+1;
  12. int c2 = 2*i+2;
  13. int max = i;
  14. if (c1<n && tree[c1] > tree[max]){
  15. max = c1;
  16. }if (c2<n && tree[c2] > tree[max]){
  17. max = c2;
  18. }if (max != i){
  19. swap(tree,max,i);
  20. heapify(tree,n,max);
  21. }
  22. }
  23. public static void swap(int[] arr,int i,int j){
  24. int temp = arr[i];
  25. arr[i] = arr[j];
  26. arr[j] = temp;
  27. }
  28. //建堆
  29. public static void build_Heap(int[] tree,int n){
  30. int last_node = n-1;
  31. int parent = (last_node-1)/2;
  32. for (int i=parent;i>=0;i--){
  33. heapify(tree,n,i);
  34. }
  35. }
  36. //堆排序
  37. public static void heap_sort(int[] tree,int n){
  38. build_Heap(tree,n);
  39. for(int i=n-1;i>=0;i--){
  40. swap(tree,i,0);//最后一个节点与第一个节点交换
  41. heapify(tree,i,0);
  42. }
  43. }
  44. public static void main(String[] args) {
  45. int[] a = { 2,5,3,1,10,4};
  46. heap_sort(a,6);
  47. for (int i=0;i<6;i++){
  48. System.out.print(a[i]+" ");
  49. }
  50. }
  51. }

发表评论

表情:
评论列表 (有 0 条评论,162人围观)

还没有评论,来说两句吧...

相关阅读

    相关 数据结构Heap

    是由完全二叉树实现的 **完全二叉树:** 若设二叉树的深度为h,除第h层外,其他各层(1—h-1)的结点数都达到最大个数,第h层所有的结点都连续集中在最左边,这就是...

    相关 数据结构-heap

    堆(heap)也被称为优先队列(priority queue)。队列中允许的操作是先进先出(FIFO),在队尾插入元素,在队头取出元素。而堆也是一样,在堆底插入元素,在堆顶取出