堆排序

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];
        }
    }


}
// heap[start...end] exclude heap[start] are satisfy the definition of heap.
// this function will adjust heap[start] to make heap as a minHeap.
public static void heapAdjust(double[] heap, int start, int end) {
    double temp = heap[start];
    for (int i = 2*start; i <= end; i*=2) {
        if (i < end && (heap[i] > heap[i + 1])) {
            i++;
        }
        if (temp < heap[i]) {
            break;
        }
        heap[start] = heap[i];
        start = i;
    }
    heap[start] = temp;
}
public static void heapSort(double[] heap) {
    for (int i = heap.length/2; i > 0; i--) {
        heapAdjust(heap, i, heap.length - 1);
    }
    for (int i = heap.length - 1; i > 1; i--) {
        double tmp = heap[1];
        heap[1] = heap[i];
        heap[i] = tmp;

        heapAdjust(heap, 1, i - 1);
    }
}

//建堆:将一个数组a[1-k]变成一个最小堆
public static void buildMinHeap(double a[],int k) {
    for (int i = k/2; i > 0; i--) {
        heapAdjust(a, i, k);
    }
}
public static void findMaxNNumber(double[] a, int n) {
    MinHeapSort.buildMinHeap(a,n);
    for (int i = n + 1; i < a.length; i++) {
        if (a[i] > a[1]) {
            double temp = a[i];
            a[i] = a[1];
            a[1] = temp;
            heapAdjust(a, 1, n);
        }
    }
    for (int i = n; i > 1; i--) {
        double tmp = a[1];
        a[1] = a[i];
        a[i] = tmp;

        heapAdjust(a, 1, i - 1);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值