Question

In: Computer Science

How Heapify is done (theory, pseudocode, and examples) the examples used Java code please

How Heapify is done (theory, pseudocode, and examples) the examples used Java code please

Solutions

Expert Solution

The biggest festival for programmers "Geek Week" is back, Enter Now!

  • search
  • Sign In
  • Home
  • Courses
  • Hire With Us
  • Algorithmskeyboard_arrow_down
  • Data Structureskeyboard_arrow_down
  • Languageskeyboard_arrow_down
  • Interview Cornerkeyboard_arrow_down
  • GATEkeyboard_arr

Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for the remaining elements.

What is Binary Heap?
Let us first define a Complete Binary Tree. A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible (Source Wikipedia)

A Binary Heap is a Complete Binary Tree where items are stored in a special order such that value in a parent node is greater(or smaller) than the values in its two children nodes. The former is called as max heap and the latter is called min-heap. The heap can be represented by a binary tree or array.

Why array based representation for Binary Heap?
Since a Binary Heap is a Complete Binary Tree, it can be easily represented as an array and the array-based representation is space-efficient. If the parent node is stored at index I, the left child can be calculated by 2 * I + 1 and right child by 2 * I + 2 (assuming the indexing starts at 0).

Heap Sort Algorithm for sorting in increasing order:
1. Build a max heap from the input data.
2. At this point, the largest item is stored at the root of the heap. Replace it with the last item of the heap followed by reducing the size of heap by 1. Finally, heapify the root of the tree.
3. Repeat step 2 while size of heap is greater than 1.

How to build the heap?
Heapify procedure can be applied to a node only if its children nodes are heapified. So the heapification must be performed in the bottom-up order.

Lets understand with the help of an example:

Input data: 4, 10, 3, 5, 1
         4(0)
        /   \
     10(1)   3(2)
    /   \
 5(3)    1(4)

The numbers in bracket represent the indices in the array 
representation of data.

Applying heapify procedure to index 1:
         4(0)
        /   \
    10(1)    3(2)
    /   \
5(3)    1(4)

Applying heapify procedure to index 0:
        10(0)
        /  \
     5(1)  3(2)
    /   \
 4(3)    1(4)
The heapify procedure calls itself recursively to build heap
 in top down manner.

// Java program for implementation of Heap Sort

public class HeapSort

{

    public void sort(int arr[])

    {

        int n = arr.length;

        // Build heap (rearrange array)

        for (int i = n / 2 - 1; i >= 0; i--)

            heapify(arr, n, i);

        // One by one extract an element from heap

        for (int i=n-1; i>0; i--)

        {

            // Move current root to end

            int temp = arr[0];

            arr[0] = arr[i];

            arr[i] = temp;

            // call max heapify on the reduced heap

            heapify(arr, i, 0);

        }

    }

    // To heapify a subtree rooted with node i which is

    // an index in arr[]. n is size of heap

    void heapify(int arr[], int n, int i)

    {

        int largest = i; // Initialize largest as root

        int l = 2*i + 1; // left = 2*i + 1

        int r = 2*i + 2; // right = 2*i + 2

        // If left child is larger than root

        if (l < n && arr[l] > arr[largest])

            largest = l;

        // If right child is larger than largest so far

        if (r < n && arr[r] > arr[largest])

            largest = r;

        // If largest is not root

        if (largest != i)

        {

            int swap = arr[i];

            arr[i] = arr[largest];

            arr[largest] = swap;

            // Recursively heapify the affected sub-tree

            heapify(arr, n, largest);

        }

    }

    /* A utility function to print array of size n */

    static void printArray(int arr[])

    {

        int n = arr.length;

        for (int i=0; i<n; ++i)

            System.out.print(arr[i]+" ");

        System.out.println();

    }

    // Driver program

    public static void main(String args[])

    {

        int arr[] = {12, 11, 13, 5, 6, 7};

        int n = arr.length;

        HeapSort ob = new HeapSort();

        ob.sort(arr);

        System.out.println("Sorted array is");

        printArray(arr);

    }


Related Solutions

How Heapify is done (theory, pseudocode, and examples) the examples used Java code please (in your...
How Heapify is done (theory, pseudocode, and examples) the examples used Java code please (in your own words)
This is an entry to Java Question. Please answer with Pseudocode and Java code for better...
This is an entry to Java Question. Please answer with Pseudocode and Java code for better understanding. We are mainly using basic in and out declarations and are focusing on API for method invocations. Any help would be very appreciated :) Problem 7: Distance (10 points) Use API (Data Science) Data Science is an emergent field from Computer Science with applications in almost every domain including finances, medical research, entertainment, retail, advertising, and insurance. The role of a data analyst...
This is an intro to java question. Please post with pseudocode and java code. Problem should...
This is an intro to java question. Please post with pseudocode and java code. Problem should be completed using repetition statements like while and selection statements. Geometry (10 points) Make API (API design) Java is an extensible language, which means you can expand the programming language with new functionality by adding new classes. You are tasked to implement a Geometry class for Java that includes the following API (Application Programming Interface): Geometry Method API: Modifier and Type Method and Description...
This is an Intro to java question. Please provide code and pseudocode for better understanding. Problem...
This is an Intro to java question. Please provide code and pseudocode for better understanding. Problem 4: Player Move Overworld (10 points) (Game Development) You're the lead programmer for an indie game studio making a retro-style game called Zeldar. You've been tasked to implement the player movement. The game is top-down, with the overworld modeled as a 2d grid. The player's location is tracked by x,y values correlating to its row and column positions within that grid. Given the current...
This is an intro to java question. Please answer with pseudocode and code. Problem 2: RSA...
This is an intro to java question. Please answer with pseudocode and code. Problem 2: RSA Public Key (10 points) (Cyber Security) RSA is an asymmetric encryption scheme, where a public key is used to encrypt data and a different, private key decrypts that data. RSA public/private keys are generated from two prime numbers, typically very large ones. The idea behind RSA is based on the fact that its difficult to factorize very large integers. RSA public key generation is...
This is an Intro to Java Question, Please respond with code and pseudocode. Problem 3: RSA...
This is an Intro to Java Question, Please respond with code and pseudocode. Problem 3: RSA Private Key (10 points) (Cyber Security) In the RSA algorithm, encrypting and decrypting a message is done using a pair of numbers that are multiplicative inverses with respect to a carefully selected modulus. In this task, you must calculate the modular multiplicative inverse for given set of values. What is the Modular Multiplicative Inverse? In mathematics, each operation typically has an inverse. For example,...
JAVA programming - please ONLY answer prompts with java code *Inheritance* will be used in code...
JAVA programming - please ONLY answer prompts with java code *Inheritance* will be used in code Classwork A zoo is developing an educational safari game with various animals. You will write classes representing Elephants, Camels, and Moose. Part A Think through common characteristics of animals, and write a class ZooAnimal. ☑ ZooAnimal should have at least two instance variables of different types (protected), representing characteristics that all animals have values for. ☑ It should also have at least two methods...
Please I can get a flowchart and a pseudocode for this java code. Thank you //import...
Please I can get a flowchart and a pseudocode for this java code. Thank you //import the required classes import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class BirthdayReminder {       public static void main(String[] args) throws IOException {        // declare the required variables String sName = null; String names[] = new String[10]; String birthDates[] = new String[10]; int count = 0; boolean flag = false; // to read values from the console BufferedReader dataIn = new BufferedReader(new...
Please can I get a flowchart and pseudocode for this java code. Thank you. TestScore.java import...
Please can I get a flowchart and pseudocode for this java code. Thank you. TestScore.java import java.util.Scanner; ;//import Scanner to take input from user public class TestScore {    @SuppressWarnings("resource")    public static void main(String[] args) throws ScoreException {//main method may throw Score exception        int [] arr = new int [5]; //creating an integer array for student id        arr[0] = 20025; //assigning id for each student        arr[1] = 20026;        arr[2] = 20027;...
Intro to java Problem, Please provide code and Pseudocode. Not able to compile correct numbers. Problem...
Intro to java Problem, Please provide code and Pseudocode. Not able to compile correct numbers. Problem 7: Simple Calculator (10 points) (General) Calculators represent the most basic, general-purpose of computing machines. Your task is to reduce your highly capable computer down into a simple calculator. You will have to parse a given mathematical expression, and display its result. Your calculator must support addition (+), subtraction (-), multiplication (*), division (/), modulus(%), and exponentiation (**). Facts ● Mathematical expressions in the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT