[email protected] Implementation of minimal heap

A binary heap is a heap data struc­ture cre­ated using a binary tree.

binary tree has two rules -

  1. Binary Heap has to be com­plete binary tree at all lev­els except the last level. This is called shape prop­erty.
  2. All nodes are either greater than equal to (Max-Heap) or less than equal to (Min-Heap) to each of its child nodes. This is called heap prop­erty.

Imple­men­ta­tion:

  • Use array to store the data.
  • Start stor­ing from index 1, not 0.
  • For any given node at posi­tion i:
  • Its Left Child is at [2*i] if available.
  • Its Right Child is at [2*i+1] if available.
  • Its Par­ent Node is at [i/2]if avail­able.

   

Heap Majorly has 3 operations -

  1. Insert Oper­a­tion
  2. Delete Oper­a­tion
  3. Extract-Min (OR Extract-Max)

Insert Oper­a­tion:

  • Add the ele­ment at the bot­tom leaf of the Heap.
  • Per­form the Bubble-Up operation.
  • All Insert Oper­a­tions must per­form the bubble-up oper­a­tion(it is also called as up-heap, percolate-up, sift-up, trickle-up, heapify-up, or cascade-up)

Bubble-up Oper­a­tion:

  • If inserted ele­ment is smaller than its par­ent node in case of Min-Heap OR greater than its par­ent node in case of Max-Heap, swap the ele­ment with its parent.
  • Keep repeat­ing the above step, if node reaches its cor­rect posi­tion, STOP.

Insert() — Bubble-Up Min-Heap

Extract-Min OR Extract-Max Operation:

  • Take out the ele­ment from the root.( it will be min­i­mum in case of Min-Heap and max­i­mum in case of Max-Heap).
  • Take out the last ele­ment from the last level from the heap and replace the root with the element.
  • Per­form Sink-Down
  • All delete oper­a­tion must per­form Sink-Down Oper­a­tion ( also known as bubble-down, percolate-down, sift-down, trickle down, heapify-down, cascade-down).

Sink-Down Oper­a­tion:

  • If replaced ele­ment is greater than any of its child node in case of Min-Heap OR smaller than any if its child node in case of Max-Heap, swap the ele­ment with its small­est child(Min-Heap) or with its great­est child(Max-Heap).
  • Keep repeat­ing the above step, if node reaches its cor­rect posi­tion, STOP.

Delete OR Extract Min from Heap

Delete Oper­a­tion:

  • Find the index for the ele­ment to be deleted.
  • Take out the last ele­ment from the last level from the heap and replace the index with this element .
  • Per­form Sink-Down

Time and Space Complexity:

Space O(n)
Search O(n)
Insert O(log n)
Delete O(log n)

package data_structure_testing;

import java.util.ArrayList;
import java.util.HashSet;

public class MinHeap {

    public ArrayList<Integer> minheap = null;

    public MinHeap() {
        this.minheap = new ArrayList<Integer> ();
        this.minheap.add(Integer.MIN_VALUE);
        /**
         * -------------------------------------------------------------------------
         * Integer.MIN_VALUE |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
         * -------------------------------------------------------------------------
         */
    }

    public void swap(int i, int j) {
        if(i == j)  return;
        int tmp = minheap.get(i);
        minheap.set(i, minheap.get(j));
        minheap.set(j, tmp);
    }

    public int getSize() {
        return minheap.size();
    }

    public int parent(int i) {
        return i/2;
    }

    public int leftChild(int i) {
        return i*2;
    }

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

    public void offer(int x) {

        minheap.add(x);
        int position = minheap.size() - 1;
        bubbleUp(position);
    }

    public void bubbleUp(int position) {

        int pa = parent(position);
        if(pa != 0 && minheap.get(position) < minheap.get(pa)) {
            swap(position, pa);
            bubbleUp(pa);
        }
    }

    public int peek() {
        if(getSize() == 1) {
            System.out.println("the min heap is empty!");
            return minheap.get(0);
        } else{
            return minheap.get(1);
        }
    }

    public void pushDown(int i) {

        int min_position = i, min_value = minheap.get(i);
        int lc = leftChild(i), rc = lc + 1;

        if(lc >= getSize()) {
            return;
        }

        if(lc < getSize()) {
            if(minheap.get(lc) < min_value) {
                min_position = lc;
                min_value = minheap.get(lc);
            }
            if(rc < getSize() && minheap.get(rc) < min_value) {
                min_position = rc;
            }
        }

        swap(min_position, i);
        if(min_position != i) {
            pushDown(min_position);
        }
    }

    public int poll() {
        if(getSize() == 1) {
            System.out.println("since the min heap is empty, so we cannot poll any element from it!");
            return minheap.get(0);
        }

        int top = minheap.get(1);
        swap(1, getSize()-1);
        minheap.remove(getSize()-1);

        if(getSize() > 1) {
            pushDown(1);
        }

        return top;
    }

    public static void main(String[] args) {

        MinHeap minheap = new MinHeap();

        minheap.offer(5);
        minheap.offer(4);
        minheap.offer(2);
        minheap.offer(4);
        minheap.offer(3);

        System.out.println(minheap.poll());
        System.out.println(minheap.poll());
        System.out.println(minheap.poll());
        System.out.println(minheap.poll());
        System.out.println(minheap.poll());
        System.out.println(minheap.poll());

    }

}

min heap

时间: 2024-10-20 17:18:55

[email protected] Implementation of minimal heap的相关文章

[email&#160;protected]关键字

// // ClassB.h // [email protected]关键字 // // Created by zhangxueming on 15/6/24. // Copyright (c) 2015年 zhangxueming. All rights reserved. // #import <Foundation/Foundation.h> #import "ClassA.h" @interface ClassB : NSObject { ClassA *_a; }

(转载)OC学习篇之[email&#160;protected]关键字的作用以及#include和#import的区别

前一篇文章说到了OC中类的三大特性,今天我们来看一下在学习OC的过程中遇到的一些问题,该如何去解决,首先来看一下我们之前遗留的一个问题: 一.#import和#include的区别 当我们在代码中使用两次#include的时候会报错:因为#include相当于拷贝头文件中的声明内容,所以会报重复定义的错误 但是使用两次#import的话,不会报错,所以他可以解决重复导入的问题,他会做一次判断,如果已经导入一次就不导入了 二.关键字@class的作用 在来看一下OC中的关键字@class的作用,在

[email&#160;protected],循环retain

2个对象互相有着引用,A中有B,B中有A. // 对于循环retain的情况,对象不能够释放,此时只能让一方使用assign一方使用retain,retain用于对象assign用于基本类型,assign时对cat的引用不会使cat对象计数器加1 Cat.h #import <Foundation/Foundation.h> @class Girl; @interface Cat : NSObject @property (nonatomic,copy)NSString *name; @pro

iOS中四种实例变量的范围类型@[email&#160;protected]@[email&#160;protected]

文档上记录是这样的 The Scope of Instance Variables To enforce the ability of an object to hide its data, the compiler limits the scope of instance variables—that is, limits their visibility within the program. 为了强制一个对象隐藏其数据,编译器限制实例变量范围以限制其在程序中的可见性 But to prov

OC学习篇之[email&#160;protected]关键字的作用以及#include和#import的区别

前一篇文章说到了OC中类的三大特性:http://blog.csdn.net/jiangwei0910410003/article/details/41707161今天我们来看一下在学习OC的过程中遇到的一些问题,该如何去解决,首先来看一下我们之前遗留的一个问题: 一.#import和#include的区别 当我们在代码中使用两次#include的时候会报错:因为#include相当于拷贝头文件中的声明内容,所以会报重复定义的错误 但是使用两次#import的话,不会报错,所以他可以解决重复导入

[email&#160;protected]、self及类的本质

让代码书写更加简便 --1-- 设置器和访问器 1.1 setter 1.2 getter --2-- 类的本质 2.1 类类型的对象 2.2 类的本质 2.3 如何获取类对象 2.4 类对象的使用 2.5 类对象的存储 --3-- SEL类型 3.1 SEL --4-- @property关键字 4.1 基本概念 4.2 @property用法 4.3 @property使用注意事项 --5-- @synthesize关键字 5.1 @synthesize用法 5.2 @synthesize使

iOS开发核心语言Objetive C —— 编译器指令@[email&#160;protected]自定义构造方法及类工厂

本分享是面向有意向从事iOS开发的伙伴们,或者已经从事了iOS的开发者.如果您对iOS开发有极高的兴趣,可以与我一起探讨iOS开发,一起学习,共同进步.如果您是零基础,建议您先翻阅我之前分享的iOS开发分分钟搞定C语言系列,然后在开始Objective C语言的学习,如果您遇到问题也可以与我探讨,另外将无偿分享自己整理的大概400G iOS学习视频及学习资料,都是干货哦!可以新浪微博私信?关注极客James,期待与您的共同学习和探讨!!由于时间有限,每天在工作之余整理的学习分享,难免有不足之处,

Realm [[email&#160;protected]] does not support authentication token

1.错误描述 [ERROR:]2015-08-03 10:03:26,508 [Realm [[email protected]] does not support authentication token [[email protected]]. Please ensure that the appropriate Realm implementation is configured correctly or that the realm accepts AuthenticationToken

记[email&#160;protected]和@Builder一起用无法添加无参构造方法的坑

转自:https://blog.csdn.net/w605283073/article/details/89221853 今天和小伙伴讨论一个mybatis-plus的一个诡异问题,最后定位到原因竟然是[email protected]和@Builder一起用无法添加无参构造方法引起的,非常隐蔽. 很多框架都是同反射等调用无参数构造方法来创建实例的,需要注意. 单独使用@Data注解,会生成无参数构造方法. // IntelliJ API Decompiler stub source gener