Skip to content

Commit

Permalink
MaxHeap remove element and Sift Down.
Browse files Browse the repository at this point in the history
  • Loading branch information
liusishan committed Feb 25, 2019
1 parent 739313a commit af9920d
Showing 1 changed file with 39 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,43 @@ private void siftUp(int k) {
}
}

// 看堆中最大元素
public E findMax() {
if (data.getSize() == 0)
throw new IllegalArgumentException("Can not findMax when head is Empty.");
return data.get(0);
}

// 取出堆中最大元素
public E extractMax() {

E ret = findMax();

data.swap(0, data.getSize() - 1);
data.removeLast();
siftDown(0);

return ret;
}

// 下沉
private void siftDown(int k) {

while (leftChild(k) < data.getSize()) {

int j = leftChild(k);
if (j + 1 < data.getSize() &&
data.get(j + 1).compareTo(data.get(j)) > 0) { // 右孩子
j = rightChild(k);
}
// data[j] 是leftChild 和rightChild中的最大值

if (data.get(k).compareTo(data.get(j)) >= 0)
break;

data.swap(k, j);
k = j;
}
}

}

0 comments on commit af9920d

Please sign in to comment.