2016-12-11 2 views
-1

Я создаю объекты типа дуги и вставить его в куче, которая должна сортировать их в порядке возрастания, но не работает выход должен бытьмин куча не работает

(B A 4) (B C 8) (B H 11) 

но это дает мне эту

(B A 4) (B H 11) (B C 8) 

это Дуга класс

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 + ")"; 
    } 
} 

это мин кучного класс

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; 
    } 
} 

ответ

3

Похоже, вы неправильно поняли концепцию мини-кучи.

Куча не сортирует элементы, это просто структура данных, которая удерживает родительский узел меньше, чем его дочерние элементы. Это не означает, что элементы хранятся в отсортированном порядке в куче. Тем не менее, это означает, что если вы реализуете метод удаления элемента min, который также работает в O(log(n)), вы можете сортировать данные в O(n log(n)), вставив каждый элемент в кучу и извлекая + удаляя их один за другим, что приводит к их возврату в по возрастанию.