堆排序(Heap-Sort)

堆排序(Heap-Sort)

(二叉)堆是一个数组,它可以被看成一颗近似的完全二叉树。树上的每个节点对应数组中一个元素。除了最底层外,该树是完全充满的,而且是从左向右填充的。堆排序是一种用堆来实现的排序算法,它的时间复杂度为O(nlgn),下面是堆排序的Java实现:


import java.util.Arrays;

/**
 * Created by CvShrimp on 2017/10/11.
 */
public class HeapSort {
    public static void maxHeap(int[] heap, int i, int endIndex) {
        int selfIndex = i - 1;
        int largest = selfIndex;
        int leftChildIndex = 2 * i - 1;
        int rightChildIndex = 2 * i;
        if(leftChildIndex <= endIndex && heap[leftChildIndex] > heap[selfIndex]) {
            largest = leftChildIndex;
        }
        if(rightChildIndex <= endIndex && heap[rightChildIndex] > heap[largest]) {
            largest = rightChildIndex;
        }
        if(largest != selfIndex) {
            swapHeapElement(heap, selfIndex, largest);
            maxHeap(heap, largest + 1, endIndex);
        }
    }

    public static void buildMaxHeap(int[] heap) {
        int startIndex = heap.length/2 - 1;
        for(int i = startIndex; i >= 0; i--) {
            maxHeap(heap, i + 1, heap.length - 1);
        }
    }

    public static void heapSort(int[] heap) {
        //构建最大堆,最大的元素在树的根节点
        buildMaxHeap(heap);
        int maxIndex = heap.length - 1;
        for(int i = maxIndex; i >= 0;) {
            //最大的元素和最后一个元素互换位置
            swapHeapElement(heap, 0, i);
            i--;
            //对剩下的前i+1个元素,再构建最大堆
            maxHeap(heap, 1, i);
        }
    }

    public static void swapHeapElement(int[] heap, int i, int j) {
        int temp = heap[i];
        heap[i] = heap[j];
        heap[j] = temp;
    }

    public static void main(String[] args) {
        int[] heap = {1,5,6,3,4,10,7,66,666,66};
        HeapSort.heapSort(heap);
        System.out.print("Sorted heap: ");
        System.out.print(Arrays.toString(heap));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值