Skip to content

Instantly share code, notes, and snippets.

@vermiculus
Created November 5, 2012 02:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vermiculus/4014954 to your computer and use it in GitHub Desktop.
Save vermiculus/4014954 to your computer and use it in GitHub Desktop.
Reverse Priority Queue (Example 4 for Alan)
import java.util.Comparator;
import java.util.PriorityQueue;
// Write a program that takes in 10 integers via command-line and prints them out in reverse natural order using a PriorityQueue. (this should use a Comparator)
public class ReversePriorityQueue
{
public class Reverse implements Comparator<Integer>
{
public int compare(Integer arg0, Integer arg1)
{
return arg1 - arg0;
}
}
public void reverseNaturalOrder(int[] a)
{
Reverse r = new Reverse();
PriorityQueue<Integer> q = new PriorityQueue<Integer>(11, r);
for(int i : a)
q.add(i);
while(!q.isEmpty())
{
System.out.println(q.poll());
}
}
public static void main(String args[])
{
int[] a = new int[args.length];
for(int i=0; i<args.length; i++)
a[i] = Integer.parseInt(args[i]);
ReversePriorityQueue x = new ReversePriorityQueue();
x.reverseNaturalOrder(a);
}
}
@artiship
Copy link

artiship commented Mar 9, 2019

PriorityQueue<Integer> reversePriorityQueue = new PriorityQueue<>((o1, o2) -> o2.compareTo(o1));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment