Question

In: Computer Science

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)

Solutions

Expert Solution

HEAP, is a data structure that is a complete binary tree. All the levels are completely filled except for the last level. Heap has some order of values to be maintained between parents and their children.

HEAPSORT is an efficient in-place comparison-based sorting algorithm and uses a data structure to achieve it. It uses a complete Binary Heap data structure to sort the elements depending on whether the heap is Min Heap (ascending) or Max heap (descending).

HEAPIFY method rearranges the elements of an array where the left and right sub-tree of ith element obeys the heap property.

ALGORITHM

  1. Max-Heapify(numbers[], i) 
    leftchild := numbers[2i] 
    rightchild := numbers [2i + 1] 
    if leftchild ≤ numbers[].size and numbers[leftchild] > numbers[i] 
       largest := leftchild 
    else 
       largest := i 
    if rightchild ≤ numbers[].size and numbers[rightchild] > numbers[largest] 
       largest := rightchild 
    if largest ≠ i 
       swap numbers[i] with numbers[largest] 
       Max-Heapify(numbers, largest)

PSEUDOCODE

procedure heapsort(array, n):
     // Step 1: creating the initial Max heap
     for i = n/2 - 1 to 0 do:
         heapify(array, n, i)
     // Step 2: Removing one element and maintaining the heap property
     for i = n-1 to 0 do:
         swap(array[0], array[i])
         heapify(array, i, 0) 
         
procedure heapify(array, n, i)
    // initialize largest as root and get left and right nodes
    int largest = i;
    int left_node = 2*i + 1;
    int right_node = 2*i + 2;
    // Check if left node exists and is larger than root. If yes, change it
    if(left_node < n && arr[left_node] > arr[largest])
        largest = left_node;
    // Check if right node exists and is larger than root. If yes, change it
    if(right_node < n && arr[right_node] > arr[largest])
        largest = right_node;
    // change root, if needed
    if(largest != i)
        swap(arr[i], arr[largest]);
        heapify(arr, n, largest);

Example:

Find the kth largest element in the array

Input : 15 35 10 6 17 11

k=3

Output: 15

Java Code:

public class HeapSort {
  
    public void sort(int arr[], int k) {
      int n = arr.length;
  
      for (int i = n / 2 - 1; i >= 0; i--) {
        heapify(arr, n, i);
      }
  
      for (int i = n - 1; i > k; i--) {
        int tmp = arr[0];
        arr[0] = arr[i];
        arr[i] = tmp;
  
        heapify(arr, i, 0);
      }
      System.out.println(arr[0]);
    }
  
    void heapify(int arr[], int n, int i) {
      int max = i;
      int leftChild = 2 * i + 1;
      int rightChild = 2 * i + 2;
  
      if (leftChild < n && arr[leftChild] > arr[max])
        max = leftChild;
  
      if (rightChild < n && arr[rightChild] > arr[max])
        max = rightChild;
  
      if (max != i) {
        int swap = arr[i];
        arr[i] = arr[max];
        arr[max] = swap;
  
        heapify(arr, n, max);
      }
    }
  
    static void display(int arr[]) {
      int n = arr.length;
      for (int i = 0; i < n; ++i)
        System.out.print(arr[i] + " ");
      System.out.println();
    }
  
    public static void main(String args[]) {
      int arr[] = {11, 34, 9, 5, 16, 10};
  
      HeapSort hs = new HeapSort();

          hs.sort(arr,3);

    }
  }

Related Solutions

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...
Intro to Java Question. Please Provide code and pseudocode for understanding. Not receiving correct results currently....
Intro to Java Question. Please Provide code and pseudocode for understanding. Not receiving correct results currently. Problem 5: Player Move Dungeon (10 points) (Game Development) You're the lead programmer at a AAA studio making a sequel to the big hit game, Zeldar 2. You've been challenged to implement player movement in dungeons. The game is top-down, with dungeons modeled as a 2d grid with walls at the edges. The player's location is tracked by x,y values correlating to its row...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT