Data Structure Learning-heap

Source: Internet
Author: User
1. Basic Introduction

The heap data structure is an array object, which can be regarded as a Complete Binary Tree. The heap access can be implemented through three functions,

parent(i)    return floor(i/2);left(i)    return 2i;right(i)    return 2i + 1;

The left operation can be completed by one step of the Left shift operation. The right operation can be performed by moving left and adding 1 to the position. The parent operation can be obtained by moving I to the right. Macro or inline functions are usually used to implement these three operations.

There are two types of binary heap: Maximum heap and minimum heap. For the largest heap

A[i] >= A[left(i)] && A[i] >= A[right(i)]

The minimum heap is

A[i] <= A[left(i)] && A[i]<= A[right(i)]

In the most heap sorting algorithm, the maximum heap is used. The minimum heap is usually used to construct a priority queue. A heap can be regarded as a tree. The height of a node in the heap is defined as the number of the longest simple descent path from the current node to the leaf. The height of the heap is defined as the height of the root tree.


2. Principles

The following describes several basic functions of the heap:

Maxheapify (), with the running time of O (lgn), is used to maintain the nature of the heap;

Bucket maxheap (), which runs in linear time, can be constructed based on unordered input arrays;

Heapsort (), with the running time of O (nlgn), sorts an array in the same place.


2.1 maintain the heap nature. The input is an array A and subscript I. When maxheapify is called, we assume that the two binary trees with leftii and right (I) as the root are the largest heap, however, a [I] may be smaller than its children, which violates the nature of the largest heap. Maxheapify "drops" a [I] in the maximum heap, making the subtree with I as the root of the heap the largest. The pseudocode is as follows.
Maxheapify (A, I) L <-left (I) r <-Right (I) if l <= heap-size [a] and a [l]> A [I] Then largest <-l else largest <-I if r <= heap-size [A] and a [R]> A [Largest] Then largest <-R if largest! = I then exchange a [I] <-> A [Largest] // exchange I and the subnode maxheapify (A, largest) larger than it; // recursive call

2.2 create a heap we can use maxheapify from the bottom up to convert an array a [1... n] (here n = length [a]) into a maximum heap. The elements in the sub-array a [floor (n/2) + 1) .. n] are all leaf nodes in the tree. Therefore, each element can be considered as a heap containing only one element. Buildmaxheap calls maxheapify once for every other node in the tree. The pseudocode is as follows.
buildMaxHeap(A)    heap-size[A] <- length[A]    for i <- floor(length[A] / 2) downto 1        do max-heapify(A,i)
When the 2.3 heap Sorting Algorithm starts, the heap sorting algorithm first uses buildmaxheap to input the array a [1 .. n] (here n = length [a]) is constructed into a maximum heap, because the maximum element in the array is in the root a [1], you can swap it with a [n] to get the final correct position. Now, if "Remove" Node N from the heap (by reducing heap-size [a]), it is easy to set a [1 .. n-1] building the largest heap, the original root child is still the largest heap, and the new root element may violate the largest heap nature. This is the maximum heap that can be maintained by calling maxheapify (A, 1). In a [1 .. (n-1)], the largest heap is constructed. The heap Sorting Algorithm repeats this process, and the heap size is reduced from n-1 to 2.
heapSort(A)    buildMaxHeap(A)    for i <- length[A] downto 2        do exchange A[1] <-> A[i]            heap-size[A] <- heap-size[A] - 1            maxHeapify(A,1)

Although the heap sorting algorithm is nice, in practice, a good implementation of fast sorting is often better than that of heap sorting.
3 JAVA Implementation 3.1 Data Structure heap. Java
import java.io.Serializable;/** * Date: 2014/8/17 * Time: 16:02 */public class Heap implements Serializable{    private int heapLength;    private int [] data;    public int getHeapLength() {        return heapLength;    }    public void setHeapLength(int heapLength) {        this.heapLength = heapLength;    }    public int[] getData() {        return data;    }    public void setData(int[] data) {        this.data = data;    }}

3.2 operation class heapsort. Java
/*** Created with intellij idea. * Date: * Time: */public class heapsort {public final static int getleft (int I) {return I <1;} public final static int getright (int I) {return (I <1) + 1;} public final static int getparent (int I) {return I> 1 ;} /*** keep heap properties ** @ Param heap * @ Param I */public static void maxheapify (heap, int I) {If (null = heap | null = heap. Getdata () | heap. getdata (). length <= 0 | I <0) return; int L = getleft (I); int r = getright (I); int largest = 0; If (L 

3.3 main. Java test class
public class Main {    public static void main(String[] args) {        int a[] = {9, 3, 4, 1, 5, 10, 7};        System.out.println("Hello World!");        Sort sort = new Sort();//        sort.bubbleSort(a);//        sort.selectSort(a);//        sort.insertionSort(a);        HeapSort.heapSort(a);        for (int i = 0; i < a.length; i++)            System.out.println(a[i]);    }}






Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.