堆排序—Java

来源:互联网 发布:淘宝网店进销存软件 编辑:程序博客网 时间:2024/06/04 23:24
package sort;


public class heapSort {
    //  前 n个是大顶堆
    static void percUp(int[] a, int n, int k){
        
        int hole = n + 1; //在数组中排第几个输, index
        while(hole/2 >= 1 && k > a[hole/2 - 1]){
                a[hole - 1] = a[hole/2 - 1];
                hole = hole/2;
        }
        a[hole - 1] = k;        
    }   //n = 0, index = 1, perfect......


    static void buildMaxHeap(int[] a){
        for(int n = 0; n<= a.length - 1; n++){
            int k = a[n];
            percUp(a, n, k);
        }
    }


    static void deleteMax(int[] a, int length){
        if( 0 == length)
            return;
        
        int lastElement = a[length -1];
        
        int result = a[0];
        int hole = 1;//  空穴的位置


        while(hole * 2 + 1 <= length){
            if(a[hole *2 -1] > lastElement || a[hole * 2] > lastElement){
                if( a[hole *2 -1] > a[hole * 2]){
                    a[hole - 1] = a[hole *2 -1];
                    hole = hole * 2;
                }
                else{
                    a[hole - 1] = a[hole* 2];
                    hole = hole * 2  + 1;
                }
            }
            else
                break;
        }
        a[hole -1] = lastElement;
        a[length -1] = result;
    }
    
    static void heapSort(int[] a){
        buildMaxHeap(a);
        
        for(int length  = a.length; length >=0; length --){
            deleteMax(a, length);
        }
    }
    
    public static void main(String[] args) {


        
        int[] array_1 = {45, 34, 23, 1, 2, 18, 80};
        int[] array_2 = {34, 23, 1, 2, 18, 80};
        int[] array_3 = {11, 12, 5, 1, 2, 3};
        int[] array_4 = {2, 2, 2, 2, 2};
        int[] array_5 = {2, 3};
        int[] array_6 = {2};
        int[] array_7 = {5, 4, 3, 2, 1};
        
        buildMaxHeap(array_1);
        buildMaxHeap(array_2);
        buildMaxHeap(array_3);
        buildMaxHeap(array_4);
        buildMaxHeap(array_5);
        buildMaxHeap(array_6);
        buildMaxHeap(array_7);
        


        heapSort(array_1);
        heapSort(array_2);
        heapSort(array_3);
        heapSort(array_4);
        heapSort(array_5);
        heapSort(array_6);
        heapSort(array_7);
        
        System.out.println("hello world");
    }


}