- public class Heap
- {
-
- public static void main(String[] args)
- {
-
-
- int []array={4,2,7,9,3,6,1,12,10,5};
- System.out.println("原始:");
- printHeapByLevel(array);
- System.out.println("最小堆:");
- getMinHeap(array);
- printHeapByLevel(array);
-
-
- sort(array);
- printHeapByLevel(array);
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public static void getMinHeap(int []array)
- {
- for(int i=1;i<array.length;i++)
- insert(array, i);
- }
-
- public static void insert(int []arrary,int k)
- {
- int insert=arrary[k];
- while(k>0)
- {
- if(insert<arrary[(k-1)/2])
- {
- arrary[k]=arrary[(k-1)/2];
- k=(k-1)/2;
- if(k==0)
- arrary[k]=insert;
- }
- else
- {
- arrary[k]=insert;
- break;
- }
- }
- }
-
- public static void printHeapByLevel(int []array)
- {
- int height=0;
- for(int i=0;i<array.length;i++)
- {
- int tempHeight=(int)(Math.log(i+1)/Math.log(2));
- if(tempHeight>height)
- {
- System.out.println();
- System.out.print(array[i]+" ");
- height=tempHeight;
- }
- else
- System.out.print(array[i]+" ");
- }
- System.out.println();
- }
-
-
-
- public static void sort(int []array)
- {
- for(int i=0;i<array.length;i++)
- {
- deleteMin(array, array.length-1-i);
- }
- }
-
-
-
-
-
-
-
-
-
-
- public static void deleteMin(int []array,int n)
- {
- int min=array[0];
- int temp=0;
- while(2*temp+1<n)
- {
- if(array[2*temp+1]>array[2*temp+2])
- {
- array[temp]=array[2*temp+2];
- temp=2*temp+2;
- }
- else
- {
- array[temp]=array[2*temp+1];
- temp=2*temp+1;
- }
- }
-
- array[temp]=array[n];
- array[n]=min;
- if(temp<n)
- insert(array, temp);
- }
- }