0
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package buildheap;

/**
 *
 * @author vladi
 */
// Java program for building Heap from Array

public class BuildHeap {

    // To heapify a subtree rooted with node i which is
    // an index in arr[].Nn is size of heap
    static 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);
        }
    }

    // Function to build a Max-Heap from the Array
    static void buildHeap(int arr[], int n)
    {
        // Index of last non-leaf node
        int startIdx = (n / 2) - 1;

        // Perform reverse level order traversal
        // from last non-leaf node and heapify
        // each node
        for (int i = startIdx; i >= 0; i--) {
            heapify(arr, n, i);
        }
    }

    // A utility function to print the array
    // representation of Heap
    static void printHeap(int arr[], int n)
    {
        System.out.println(
            "Array representation of Heap is:");

        for (int i = 0; i < n; ++i)
            System.out.print(arr[i] + " ");

        System.out.println();
    }

    // Driver Code
    public static void main(String args[])
    {
        
        int arr[] = { 5,4,7,2,6,9 };
                

        int n = arr.length;

        buildHeap(arr, n);

        printHeap(arr, n);
    }
}

Hello i am trying to build a maxheap but i am stuck on how can i use strings instead of numbers i want to put in each node 2 strings (the word and it's definition) for example in the first node i want to add ("Apple:fruit usally rounded red") and i want to heapify them alphabetically. so should i do an array of objects or string? and how can i use in in this code?

nodedata
  • 13
  • 3
  • If you try to use the same code for strings, you will run into a problem with `` comparisons. [Strings have compareTo](https://stackoverflow.com/q/5153496/14215102). If you want to make a thing that has two strings in it, a tiny `class` should work fine. –  Jan 07 '22 at 16:14
  • How is building a dictionary (mentioned in the title) related to your heap? A heap is the wrong data structure for implementing a dictionary. – trincot Jan 08 '22 at 11:42

0 Answers0