用java实现二叉查找树、堆和优先队列
作者:网络转载 发布时间:[ 2013/2/6 9:48:31 ] 推荐标签:
下面设计和实现Heap类。
package heap;
import java.util.ArrayList;
public class Heap {
private ArrayList list = new ArrayList();
public Heap() {
}
public Heap(Object[] objects) {
for (int i = 0; i < objects.length; i++) {
add(objects[i]);
}
}
public void add(Object newObject) {
list.add(newObject);
//the index of the last node
int currentIndex = list.size() - 1;
while (currentIndex > 0) {
//计算父节点的index
int parentIndex = (currentIndex - 1) / 2;
//如果当前节点大于他的父节点交换
if (((Comparable) (list.get(currentIndex))).compareTo(list
.get(parentIndex)) > 0) {
Object temp = list.get(currentIndex);
list.set(currentIndex, list.get(parentIndex));
list.set(parentIndex, temp);
} else {
break;
}
currentIndex = parentIndex;
}
}
/**
* remove the root from the heap
*
* @return
*/
public Object remove() {
if (list.size() == 0) {
return null;
}
//被删除的节点---根节点
Object removedObject = list.get(0);
//将后一个移动到根节点
list.set(0, list.get(list.size() - 1));
list.remove(list.size() - 1);
int currentIndex = 0;
while (currentIndex < list.size()) {
//计算当前节点的左节点和右节点
int leftChildIndex = 2 * currentIndex + 1;
int rightChileIndex = 2 * currentIndex + 2;
//找到两个子节点中大的节点
if (leftChildIndex >= list.size()) {
break;
}
int maxIndex = leftChildIndex;
if (rightChileIndex < list.size()) {
if (((Comparable) (list.get(maxIndex))).compareTo(list
.get(rightChileIndex)) < 0) {
maxIndex = rightChileIndex;
}
}
//如果当前节点小于子节点的大值交换
if (((Comparable) (list.get(currentIndex))).compareTo(list
.get(maxIndex)) < 0) {
Object temp = list.get(maxIndex);
list.set(maxIndex, list.get(currentIndex));
list.set(currentIndex, temp);
currentIndex = maxIndex;
} else {
break;
}
}
return removedObject;
}
public int getSize() {
return list.size();
}
}
测试类:
package heap;
public class TestHeap {
public static void main(String[] args) {
Heap heap = new Heap(new Integer[] { 8, 9, 2, 4, 5, 6, 7, 5, 3, 0 });
while (heap.getSize() > 0) {
System.out.println(heap.remove() + " ");
}
}
}
相关推荐
更新发布
功能测试和接口测试的区别
2023/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11