zoukankan      html  css  js  c++  java
  • 堆与优先级队列 沧海

    最大值堆(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
  • 相关阅读:
    C# WPF 窗体传递消息
    WPF ProgressBar 样式
    WPF的TextBox以及PasswordBox显示水印文字
    Win8.1 Hyper-V 共享本机IP上网
    ASP.NET MVC入门-Startup 类:注册服务和使用中间件
    ASP.NET MVC入门-Program类:程序的入口
    Unity3d AssetBundle 资源加载与管理
    C#考核知识点总结
    数据结构与算法之美-字符串匹配(上)
    LeetCode-探索链表-综合问题
  • 原文地址:https://www.cnblogs.com/omygod/p/554627.html
Copyright © 2011-2022 走看看