我正在创建弧类型的对象并将其插入到堆中,堆应该按升序对它们进行排序,但不能正常输出
(B A 4) (B C 8) (B H 11)
但它给了我这个
(B A 4) (B H 11) (B C 8)
这是Arc class
public static class Arc implements Comparable<Arc> {
/**
* A vertex at one end of this arc.
*/
Vertex v1;
/**
* A vertex at one end of this arc.
*/
Vertex v2;
/**
* Weight assigned to this arc.
*/
int weight;
/**
* Constructs a new Arc object from an existing edge in a graph.
*
* @param v1 Vertex at one end of the edge.
* @param v2 Vertex at the other end of the edge.
* @param weight Weight of the edge.
*/
public Arc(Vertex v1, Vertex v2, int weight) {
this.v1 = v1;
this.v2 = v2;
this.weight = weight;
}
@Override
public boolean equals(Object o) {
if (o == null || !(o instanceof Arc)) {
return false;
}
Arc other = (Arc)o;
return weight == other.weight &&
((v1.name.equals(other.v1.name) && v2.name.equals(other.v2.name)) ||
(v1.name.equals(other.v2.name) && v2.name.equals(other.v1.name)));
}
/**
* Compares the weight of this arc with that of another.
*
* @param other Other arc
* @return 0 if the weights are equal, +ve if this arc's weight is greater, -ve otherwise
*
*/
@Override
public int compareTo(Arc other) {
return weight - other.weight;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "(" + v1 + " " + v2 + " " + weight + ")";
}
}
这是min heap class
public class MinHeap<T extends Comparable<T>> implements Iterable<T> {
private ArrayList<T> items;
/**
* Constructs a new, empty heap with an initial capacity of 10
*/
public MinHeap() {
this(10);
}
public void siftUp(int k) { // sift up starting at k
while (k > 0) {
int p = (k-1)/2;
int c = items.get(k).compareTo((items.get(p)));
if (c < 0) {
T temp = items.get(k);
items.set(k, items.get(p));
items.set(p, temp);
k = p;
} else {
break;
}
}
}
/**
* Inserts an item into the heap.
*
* @param item Item to insert.
*/
public void insert(T item) {
items.add(item);
siftUp(items.size()-1);
}
/**
* Returns (but does not remove) the min item in the heap.
*
* @return Item at top of heap.
* @throws NoSuchElementExcepton If heap is empty.
*/
public T getMin() throws NoSuchElementException {
if (items.isEmpty()) {
throw new NoSuchElementException();
}
return items.get(0);
}
public String toString() {
String ret = "";
for (T item: items) {
ret += " " + item;
}
return ret;
}
}
答案 0 :(得分:3)
好像你误解了最小堆的概念。
堆不对元素进行排序,它只是一个数据结构,它使父节点小于它的子节点。这并不意味着元素以堆中的排序顺序存储。但是,它确实意味着如果您实现一个方法来删除也在O(log(n))
中运行的min元素,您可以通过将每个项目插入堆中并检索+逐个删除它们来对O(n log(n))
中的数据进行排序,导致它们按升序返回。