• 堆与优先级队列 沧海


    最大值堆(MAX-HEAP)的性质是任意一个结点的值都大于或者等于其任意一个子结点存储的值。由于根结点包含大于或等于其子结点的值,而其子结点又依次大于或者等于各自结点的值,所以根结点存储着该树的所有结点中的最大值。

    最小值堆(MIN-HEAP)的性质是任意一个结点的值都小于或者等于其子结点存储的值。

    无论最小值堆还是最大值堆,任何一个结点与其兄弟之间都没有必然的联系。

    public class MaxHeap {

    private Element[] heap;

    private int maxSize;

    private int size;

    public MaxHeap(Element[] heap, int size, int maxSize) {
    this.heap = heap;
    this.size = size;
    this.maxSize = maxSize;
    }

    public int size() {
    return this.size;
    }

    public boolean isLeaf(int position) {
    return (position >= size / 2) && (position < size);
    }

    public int leftChild(int position) {
    return 2 * position + 1;
    }

    public int rightChild(int position) {
    return 2 * position + 2;
    }

    public int parent(int position) {
    return (position - 1) / 2;
    }

    public void buildheap() {
    for (int i = size / 2; i >= 0; i--) {
    siftdown(i);
    }
    }

    private void siftdown(int position) {
    while (!isLeaf(position)) {
    int j = leftChild(position);
    if ((j < (size - 1)) && (heap[j].getKey() < heap[j + 1].getKey())) {
    j++;
    }
    if (heap[j].key >= heap[j + 1].getKey()) {
    return;
    }
    swap(position, j);
    position = j;
    }
    }

    public void insert(Element element) {
    int position = size++;
    heap[position] = element;
    while ((position != 0)
    && (heap[position].getKey() > heap[parent(position)].getKey())) {
    swap(position, parent(position));
    position = parent(position);
    }
    }

    public Object removeMax() {
    return remove(0);
    }

    public Object remove(int position) {
    swap(position, --size);
    if (size != 0) {
    siftdown(position);
    }
    return heap[size];
    }

    private void swap(int src, int dest) {
    Element element = heap[src];
    heap[src] = heap[dest];
    heap[dest] = element;
    }

    /**
    * @param args
    */
    public static void main(String[] args) {
    // TODO Auto-generated method stub

    }

    public class Element {
    private Object value;

    private int key;

    public Element() {

    }

    public int getKey() {
    return key;
    }

    public void setKey(int key) {
    this.key = key;
    }

    public Object getValue() {
    return value;
    }

    public void setValue(Object value) {
    this.value = value;
    }

    }
    }
    专注于企业信息化,最近对股票数据分析较为感兴趣,可免费分享股票个股主力资金实时变化趋势分析工具,股票交流QQ群:457394862
  • 相关阅读:
    flash编程实例源代码下载
    js4:with,for in语句,windows,location对象的使用
    js3:数据类型,数组,String各个属性,以及字符串表达式用eval计算
    挺喜欢这个网站的
    C#Url传递中文参数时解决方法
    .NET设计模式系列文章《转》
    maven surefire plugin介绍
    spring-boot-maven-plugin 插件的作用
    github提交表情包
    接口管理工具
  • 原文地址:https://www.cnblogs.com/omygod/p/554627.html
Copyright © 2020-2023  润新知