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 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,...
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...
This is done by using Angular in Visual code: Can you please give examples of the...
This is done by using Angular in Visual code: Can you please give examples of the following? 1. Use Math.random function to generate a number between 20 and 100 and then use the ngSwitch directive to display a letter grade based on this class grading policy. a. add implements OnInit to the AppComponent class b. add variable x in the AppComponent class c. add ngOnInit(){ this.x = Math.floor(Math.random()*10);} d. add {{x}} in the app.components.html file e. You should see numbers...
PYTHON ONLY NO JAVA! PLEASE INCLUDE PSEUDOCODE AS WELL! Program 4: Design (pseudocode) and implement (source...
PYTHON ONLY NO JAVA! PLEASE INCLUDE PSEUDOCODE AS WELL! Program 4: Design (pseudocode) and implement (source code) a program (name it LargestOccurenceCount) that read from the user positive non-zero integer values, finds the largest value, and counts it occurrences. Assume that the input ends with number 0 (as sentinel value to stop the loop). The program should ignore any negative input and should continue to read user inputs until 0 is entered. The program should display the largest value and...
write JAVA code with the following condition Write the pseudocode for a new data type MyStack...
write JAVA code with the following condition Write the pseudocode for a new data type MyStack that implements a stack using the fact that you have access to a queue data structure with operations enqueue(), dequeue(), isEmpty(). Remember that every stack should have the operations push() and pop(). Hint: use two queues, one of which is the main one and one is temporary. Please note that you won’t be able to implement both push() and pop() in constant time. One...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT