Skip to content

Commit

Permalink
update MaxHeap
Browse files Browse the repository at this point in the history
  • Loading branch information
l81893521 committed May 21, 2018
1 parent 8758ac0 commit b1262c3
Show file tree
Hide file tree
Showing 3 changed files with 102 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,4 @@

### 优先队列和堆
1. [堆的基本定义](https://github.com/l81893521/basic-data-structure/blob/master/src/main/java/will/zhang/heap/AMaxHeap.java)
1. [往堆中添加元素和siftUp](https://github.com/l81893521/basic-data-structure/blob/master/src/main/java/will/zhang/heap/BMaxHeap.java)
14 changes: 14 additions & 0 deletions src/main/java/will/zhang/heap/Array.java
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,20 @@ public void add(int index, T e){

}

/**
* 交换索引i和索引j的元素
* @param i
* @param j
*/
public void swap(int i, int j){
if(i < 0 || j < 0 || i >= size || j >= size){
throw new IllegalArgumentException("Index is illegal");
}
T t = data[i];
data[i] = data[j];
data[j] = t;
}

@Override
public String toString(){
StringBuilder builder = new StringBuilder();
Expand Down
87 changes: 87 additions & 0 deletions src/main/java/will/zhang/heap/BMaxHeap.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package will.zhang.heap;

/**
* 使用数组实现最大堆
* @param <E>
*/
public class BMaxHeap<E extends Comparable<E>> {

//存放数据
private Array<E> data;

public BMaxHeap(int capacity){
data = new Array<>(capacity);
}

public BMaxHeap(){
data = new Array<>();
}

/**
* 获取堆的大小
* @return
*/
public int size(){
return data.getSize();
}

/**
* 返回堆是否为空
* @return
*/
public boolean isEmpty(){
return data.isEmpty();
}

/**
* 返回父亲节点的索引
* @param index
* @return
*/
private int parent(int index){
if(index == 0){
throw new IllegalArgumentException("index-0 doesn't have parent.");
}
return (index - 1) / 2;
}

/**
* 返回左孩子节点的索引
* @param index
* @return
*/
private int leftChild(int index){
return index * 2 + 1;
}

/**
* 返回右孩子节点的索引
* @param index
* @return
*/
private int rightChild(int index){
return index * 2 + 2;
}

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

/**
* 堆的核心方法, 元素上浮至适当位置(符合堆的定义的位置, 比父亲节点小并且比孩子节点大)
* @param k
*/
private void siftUp(int k) {
//如果当前k比父亲节点parent(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 b1262c3

Please sign in to comment.