Skip to content

Commit

Permalink
MaxHeap add element and Sift Up.
Browse files Browse the repository at this point in the history
Array swap().
  • Loading branch information
liusishan committed Feb 25, 2019
1 parent 95af751 commit 739313a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,17 @@ public void removeElement(E e) {
remove(index);
}

// 交换两元素的位置
public void swap(int i, int j) {

if (i < 0 || i >= size || j < 0 || j >= size)
throw new IllegalArgumentException("Index is illegal.");

E t = data[i];
data[i] = data[j];
data[j] = t;
}

@Override
public String toString() {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,19 @@ private int rightChild(int index) {
return index * 2 + 2;
}

// 向堆中添加元素
public void add(E e) {
data.addLast(e);
siftUp(data.getSize() - 1);
}

// 上浮操作
private void siftUp(int k) {

while (k > 0 && data.get(parent(k)).compareTo(data.get(k)) < 0) {
data.swap(k, parent(k));
k = parent(k);
}
}

}

0 comments on commit 739313a

Please sign in to comment.