Last active
December 19, 2021 10:29
-
-
Save sunmeat/783b114af31a938c9a2750fcffc0160c to your computer and use it in GitHub Desktop.
exclusion priority queue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package collections; | |
import java.util.Random; | |
class PriorityQueue { | |
private int[] data; | |
private int[] priorities; | |
private int maxCount; | |
private int count = 0; | |
public PriorityQueue(int max) { | |
if (max < 10) { | |
max = 10; | |
} | |
maxCount = max; | |
data = new int[max]; | |
priorities = new int[max]; | |
} | |
public void clear() { | |
count = 0; | |
} | |
public boolean isEmpty() { | |
return count == 0; | |
} | |
public boolean isFull() { | |
return count == maxCount; | |
} | |
public int getCount() { | |
return count; | |
} | |
public void enqueue(int value, int priority) { | |
if (!isFull()) { | |
data[count] = value; | |
priorities[count] = priority; | |
count++; | |
} | |
} | |
public int dequeue() { | |
if (!isEmpty()) { | |
int maxPriority = priorities[0]; | |
int maxPriorityPosition = 0; | |
for (int i = 1; i < count; i++) { | |
if (maxPriority < priorities[i]) { | |
maxPriority = priorities[i]; | |
maxPriorityPosition = i; | |
} | |
} | |
int result = data[maxPriorityPosition]; | |
for (int i = maxPriorityPosition; i < count - 1; i++) { | |
data[i] = data[i + 1]; | |
priorities[i] = priorities[i + 1]; | |
} | |
count--; | |
return result; | |
} | |
return -1; | |
} | |
public void print() { | |
System.out.println("================================="); | |
for (int i = 0; i < count; i++) { | |
System.out.println(data[i] + " with priority " + priorities[i]); | |
} | |
System.out.println("=================================\n"); | |
} | |
} | |
/////////////////////////////////////////////////////////////////////////// | |
class Program { | |
public static void main(String[] args) { | |
Random r = new Random(); | |
PriorityQueue q = new PriorityQueue(20); | |
for (int i = 0; i < 7; i++) { | |
q.enqueue(r.nextInt(500), r.nextInt(10)); | |
} | |
q.print(); | |
for (int i = 0; i < 4; i++) { | |
q.dequeue(); | |
} | |
q.print(); | |
for (int i = 0; i < 3; i++) { | |
q.enqueue(r.nextInt(500), r.nextInt(10)); | |
} | |
q.print(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment