??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