1. 程式人生 > >奮鬥的小飛蟲,堅持堅持

奮鬥的小飛蟲,堅持堅持

public class HeapSort {

    public static void minHeap(double a[],int index, int k) {
        int MinIndex = index;
        int LeftIndex = 2*index;
        int RightIndex = 2*index+1;
        if(LeftIndex <= k && a[LeftIndex] < a[MinIndex]){
            MinIndex = LeftIndex;
        }
        if(RightIndex <= k && a[RightIndex] < a[MinIndex]){
            MinIndex = RightIndex;
        }

        double temp;
        if(MinIndex != index){
            temp = a[index];
            a[index] = a[MinIndex];
            a[MinIndex] = temp;
            minHeap(a,MinIndex,k);
        }
    }

    //建堆:將一個數組a[1-k]變成一個最小堆
    public static void buildMinHeap(double a[],int k){
        int i;
        //用容量為k的最小堆來儲存最大的k個數
        for(i = k;i >= 1;i--){
            minHeap(a,i,k);
        }
    }

    public static void findMaxKNumber(double[] a, int k, double[] maxK) {
        HeapSort.buildMinHeap(a,k);
        for(int i = a.length - 1; i > k; i--){
            double temp;
            if(a[1] < a[i]){
                temp = a[i];
                a[i] = a[1];
                a[1] = temp;
                HeapSort.minHeap(a,1,k);
            }
        }
        for(int i = 1;i <= k;i++){
            maxK[i - 1] = a[i];
        }
    }


}