2016-10-09 7 views
0

Я пытаюсь реализовать приоритетную очередь, которая будет упорядочивать HashSets в порядке их размера (то есть наименьший HashSets будет иметь наивысший приоритет).Java: как приоритетная очередь HashSet в порядке SIZE (наименьшая первая)?

Как я могу реализовать это на Java?

Ниже приведена моя попытка, которая успешно упорядочивает HashSets по их приоритетному номеру (сначала по высоте).

Мой главный метод:

 System.out.print("Enter size of priority queue: "); 
     int inputSize = scanner.nextInt(); 

     HashSetQueue pq = new HashSetQueue(inputSize); 

     System.out.println("1. insert"); 
     System.out.println("2. remove"); 
     System.out.println("3. check empty"); 
     System.out.println("4. check full"); 
     System.out.println("5. empty"); 
     System.out.println("6. check size"); 
     System.out.println("7. print"); 
     System.out.print("Please enter a number: "); 

     int choice = scanner.nextInt(); 
     switch (choice) { 
     case 1: 
      System.out.print("Please enter a value: "); 
      int userInput = scanner.nextInt(); 

      HashSet<Integer> set = new HashSet<Integer>(); 
      set.add(userInput); 

      System.out.println("Please enter a priority: "); 
      int priority = scanner.nextInt(); 

      pq.insert(priority, set); 
      break; 
     case 2: 
      System.out.println("\nJob removed \n\n" + pq.remove()); 
      break; 
     case 3: 
      System.out.println("\nEmpty Status: " + pq.isEmpty()); 
      break; 
     case 4: 
      System.out.println("\nFull Status: " + pq.isFull()); 
      break; 
     case 5: 
      System.out.println("\nPriority Queue Cleared!"); 
      pq.clear(); 
      break; 
     case 6: 
      System.out.println("\nSize = " + pq.size()); 
      break; 
     case 7: 
      pq.print(); 
      break; 
     default: 
      System.out.println("\nPlease enter a valid number on the list!"); 
      break; 

Мой PriorityQueue класс

import java.util.HashSet; 

/** class Task **/ 
class Task { 
    int priority; 
    HashSet<Integer> job; 

    /** Constructor **/ 
    public Task(int priority, HashSet<Integer> job) { 
    this.job = job; 
    this.priority = priority; 
    } 

    /** toString() **/ 
    public String toString() { 
    return "\nPriority : " + priority + "\nJob Name : " + job; 
    } 
} 

/** Class PriorityQueue **/ 
class HashSetQueue { 
    private Task[] heap; 
    private int heapSize, capacity; 

    /** Constructor **/ 
    public HashSetQueue(int capacity) { 
    this.capacity = capacity++; 
    heap = new Task[this.capacity]; 
    heapSize = 0; 
    } 

    /** function to clear **/ 
    public void clear() { 
    heap = new Task[capacity]; 
    heapSize = 0; 
    } 

    /** function to check if empty **/ 
    public boolean isEmpty() { 
    return heapSize == 0; 
    } 

    /** function to check if full **/ 
    public boolean isFull() { 
    return heapSize == capacity - 1; 
    } 

    /** function to get Size **/ 
    public int size() { 
    return heapSize; 
    } 

    public void print() { 
    Task item; 

    for (int i = 1; i <= heapSize; i++) { 
     item = heap[i]; 
     System.out.println(item); 
    } 
    } 

    /** function to insert task **/ 
    public void insert(int priority, HashSet<Integer> job) { 
    Task newJob = new Task(priority, job); 

    heap[++heapSize] = newJob; 
    int pos = heapSize; 
    while (pos != 1 && newJob.priority > heap[pos/2].priority) { 
     heap[pos] = heap[pos/2]; 
     pos /= 2; 
    } 
    heap[pos] = newJob; 
    } 

    /** function to remove task **/ 
    public Task remove() { 
    int parent, child; 
    Task item, temp; 
    if (isEmpty()) { 
     System.out.println("Heap is empty"); 
     return null; 
    } 

    item = heap[1]; 
    temp = heap[heapSize--]; 

    parent = 1; 
    child = 2; 
    while (child <= heapSize) { 
     if (child < heapSize && heap[child].priority < heap[child + 1].priority) 
     child++; 
     if (temp.priority >= heap[child].priority) 
     break; 

     heap[parent] = heap[child]; 
     parent = child; 
     child *= 2; 
    } 
    heap[parent] = temp; 

    return item; 
    } 
} 
+0

Почему бы не использовать [ 'PriorityQueue'] (https: // документы .oracle.com/JavaSE/8/документы/API/Java/Util/PriorityQueue.html)? –

+0

@ElliottFrisch Сколько я реализую очередь приоритетов, которая заказывает HashSet по размеру? Я не знаком с функцией компаратора для PriorityQueue! – Tai

+0

Используйте PriorityQueue со своим собственным компаратором: PriorityQueue (компаратор компаратор) https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html. – kamalkishor1991

ответ

0

Я думаю, что вам нужно изменить эту строку:

while (pos != 1 && newJob.priority > heap[pos/2].priority) { 

к:

while (pos != 1 && newJob.job.size() < heap[pos/2].job.size()) { 

это добавит новую задачу перед выполнением других задач с большим количеством заданий.

С другой стороны, если это не для цели образования, то не пытайтесь изобретать велосипед и просто использовать PriorityQueue с вашим Comparator