最大堆
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了最大堆相关的知识,希望对你有一定的参考价值。
二叉堆:
堆排序时间复杂度O(nlgn)
1 package com.bing; 2 3 import java.util.Arrays; 4 //ywb 5 public class HeapSort { 6 7 8 //首先假设 以left(i) ,right(i) 为根节点的子树满足最大堆性质 9 public static <T extends Comparable<? super T>> void max_HeapIf_Y(T[] A,int i,int heapSize) 10 { 11 int l=left(i),r=right(i),largest; 12 if(l<=heapSize && A[i].compareTo(A[l])<0) 13 { 14 largest = l; 15 }else 16 { 17 largest = i; 18 } 19 if(r<=heapSize && A[largest].compareTo(A[r])<0) 20 { 21 largest = r; 22 } 23 if(largest!=i) 24 { 25 exchange(A,i,largest); 26 max_HeapIf_Y(A,largest,heapSize); 27 } 28 29 } 30 31 public static <T extends Comparable<? super T>> void build_max_heap(T[] A,int heapSize) 32 { 33 34 for(int i=A.length/2;i>=0;i--) 35 { 36 max_HeapIf_Y(A,i,heapSize); 37 } 38 } 39 40 public static <T extends Comparable<? super T>> void heapSort(T[] A) 41 { 42 build_max_heap(A,A.length-1); 43 int heapSize = A.length-1; 44 for(int i=A.length-1;i>=1;i--) 45 { 46 exchange(A,0,i); 47 heapSize--; 48 max_HeapIf_Y(A,0,heapSize); 49 } 50 } 51 public static void main(String[] args) { 52 Integer[] a = {8,9,6,3,7,0,2,15,-1,8,8,28,4,0,45,78,22 53 ,2000,3243,4,0,4,4,48,3,33,55,11,22,9}; 54 System.out.println(Arrays.toString(a)); 55 long start = System.nanoTime(); 56 heapSort(a); 57 long end = System.nanoTime(); 58 System.out.println(Arrays.toString(a)); 59 System.out.println(end - start); 60 61 } 62 public static int left(int i) 63 { 64 return 2*i+1; 65 } 66 public static int right(int i) 67 { 68 return 2*i+2; 69 } 70 public static int parent(int i) 71 { 72 return i/2; 73 } 74 public static <T> void exchange(T[] A,int i,int j){ 75 T temp = A[i]; 76 A[i] = A[j]; 77 A[j] = temp; 78 } 79 80 }
以上是关于最大堆的主要内容,如果未能解决你的问题,请参考以下文章