从给定节点开始的堆检查节点的每个子节点,如果它大于父节点,则交换这两个子节点并堆检查子节点
/* 来 自 n o w j a v a . c o m*/ //package com.nowjava; public class Main { /** * heapifies starting from a given node * * heapifying checks each child of the node and if it is greater than the * parent it swaps the two and heapifies the child * * @param heap * the heap to heapify in * @param index * the index of the node to heapify * @param heapSize * the size of the heap */ public static void heapify(Comparable[] heap, int index, int heapSize) { int leftIndex = 2 * index; int rightIndex = 2 * index + 1; if (leftIndex <= heapSize) { if (heap[leftIndex].compareTo(heap[index]) > 0) { swap(heap, index, leftIndex); heapify(heap, leftIndex, heapSize); } } if (rightIndex <= heapSize) { if (heap[rightIndex].compareTo(heap[index]) > 0) { swap(heap, index, rightIndex); /** 时代Java - nowjava.com 提供 **/ heapify(heap, rightIndex, heapSize); } } }