Vamos ver agora como implementar esse método em Java. Para isso, vamos implementar uma classe chamada Heap. A classe possui dois métodos principais:

O primeiro método é o constructo, que constrói um heap com N elementos:

Exemplo 1_3_5: exemplo de busca heapSort.

private void construct() {
    int current, maxChildIndex;
    boolean done;
    for (int i = (heap.length - 2) / 2; i >= 0; i--) {
        current = i;
        done = false;
        while (!done) {// constroi o heap
            // com o nó no índice i
            if (2 * current + 1 > heap.length - 1) {
            // o nó atual não tem filho, então pára
            done = true;
            } else {
              // o nó atual tem pelo menos um nó filho
              // busca o índice do maior filho
              maxChildIndex=maxChild(current, heap.length - 1);
              if (heap[current] < heap[maxChildIndex]) {
             // o nó filho é maior, então troca e continua
                swap(current, maxChildIndex);
                current = maxChildIndex;
              } else { // se todos os nós tiverem a condição 
                // de valor satisfeita então para
                done = true;
                }
                    }
          }
    assert isValidHeap(heap, i, heap.length - 1) : "Error: Construction phase is not working "
                    + "correctly";
    }
        testPrint(heap.length); // TEMP
}
Copyright © 2014 AIEC.