我有一个同学写的代码。问题是我无法理解SORT方法的作用。据我所知,它命令优先级队列没有被修改。相反,heapify方法是一种有助于操纵堆的方法(在本例中为MIN HEAP),它允许元素A [i]向下滚动堆,直到到达正确位置为止。我错了吗?package priorityQueue;import java.util.ArrayList;import java.util.Comparator;import java.util.HashMap;import java.util.NoSuchElementException;public class BinaryHeap {protected static <P,E> Element<P,E> extractMinimum(ArrayList<Element<P, E>> priorityQueue, Comparator<Element<P,E>> priorityComparator, HashMap<E, Integer> mapping) throws NoSuchElementException { if (priorityQueue.size() == 0) throw new NoSuchElementException(); if (priorityQueue.size() == 1) return priorityQueue.remove(0); Element<P,E> first = priorityQueue.get(0); mapping.remove(first.getElement()); Element<P,E> newFirst = priorityQueue.get(priorityQueue.size()-1); mapping.remove(newFirst.getElement()); priorityQueue.set(0, priorityQueue.remove(priorityQueue.size()-1)); mapping.put(newFirst.getElement() , 0); heapify(priorityQueue, priorityComparator, mapping,0); return first;}protected static <P,E> void sort (ArrayList<Element<P, E>> priorityQueue, Comparator<Element<P,E>> priorityComparator, HashMap<E, Integer> mapping, int index) { int i = index; while(i > 0) { int middle = (i - 1)/2; Element<P,E> element = priorityQueue.get(i); Element<P,E> parent = priorityQueue.get(middle); if(priorityComparator.compare(element, parent)<0) { mapping.replace(element.getElement(), middle); mapping.replace(parent.getElement(), i); priorityQueue.set(i, parent); priorityQueue.set(middle, element); i = middle; } else break; }}
添加回答
举报
0/150
提交
取消