* 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);
}
}
您好,我正在尝试构建一个 maxheap,但我被困在如何使用字符串而不是数字我想在每个节点中放入 2 个字符串(单词及其定义),例如在我要添加的第一个节点中(“Apple :fruit 通常是圆形的红色") 我想按字母顺序排列它们。那么我应该做一个对象数组还是字符串?我如何在这段代码中使用?