insert will insert the item into the heap - Java Collection Framework

Java examples for Collection Framework:Heap

Description

insert will insert the item into the heap

Demo Code


//package com.java2s;

public class Main {
    /**/*from  w  w  w .  jav  a  2  s .c om*/
     * insert will insert the item into the heap
     * 
     * @param heap
     *            is the heap into which item is to be inserted in
     * @param item
     *            is the item to be inserted into heap
     * @param heapSize
     *            the size of the heap
     * @return return the new heap
     */
    public static Comparable[] insert(Comparable[] heap, Comparable item,
            int heapSize) {
        Comparable[] nHeap = new Comparable[heapSize + 2];
        for (int i = 1; i <= heapSize; i++) {
            nHeap[i] = heap[i];
        }
        nHeap[heapSize + 1] = item;
        buildHeap(nHeap, heapSize + 1);
        return nHeap;
    }

    /**
     * builds the heap using the heapify method
     * 
     * @param heap
     *            is the heap to be built
     * @param heapSize
     *            is the size of the heap
     */
    public static void buildHeap(Comparable[] heap, int heapSize) {
        for (int i = heapSize / 2; i > 0; i--) {
            heapify(heap, i, heapSize);
        }
    }

    /**
     * heapifies starting from a given node
     * 
     * heapifying checks each child of the node and if it is greater than the
     * parent it swaps the two and heapifies the child
     * 
     * @param heap
     *            the heap to heapify in
     * @param index
     *            the index of the node to heapify
     * @param heapSize
     *            the size of the heap
     */
    public static void heapify(Comparable[] heap, int index, int heapSize) {
        int leftIndex = 2 * index;
        int rightIndex = 2 * index + 1;
        if (leftIndex <= heapSize) {
            if (heap[leftIndex].compareTo(heap[index]) > 0) {
                swap(heap, index, leftIndex);
                heapify(heap, leftIndex, heapSize);
            }
        }
        if (rightIndex <= heapSize) {
            if (heap[rightIndex].compareTo(heap[index]) > 0) {
                swap(heap, index, rightIndex);
                heapify(heap, rightIndex, heapSize);
            }
        }
    }

    /**
     * swap will swap the elements in heap at index and index2
     * 
     * @param heap
     *            is the heap to be switched
     * @param index
     *            is the first element to be switched
     * @param index2
     *            is the second element to be switched
     */
    public static void swap(Comparable[] heap, int index, int index2) {
        Comparable temp = heap[index];
        heap[index] = heap[index2];
        heap[index2] = temp;
    }
}

Related Tutorials