Java Priority Queue Comparator - java

I have defined my own compare function for a priority queue, however the compare function needs information of an array. The problem is that when the values of the array changed, it did not affect the compare function. How do I deal with this?
Code example:
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner;
public class Main {
public static final int INF = 100;
public static int[] F = new int[201];
public static void main(String[] args){
PriorityQueue<Integer> Q = new PriorityQueue<Integer>(201,
new Comparator<Integer>(){
public int compare(Integer a, Integer b){
if (F[a] > F[b]) return 1;
if (F[a] == F[b]) return 0;
return -1;
}
});
Arrays.fill(F, INF);
F[0] = 0; F[1] = 1; F[2] = 2;
for (int i = 0; i < 201; i ++) Q.add(i);
System.out.println(Q.peek()); // Prints 0, because F[0] is the smallest
F[0] = 10;
System.out.println(Q.peek()); // Still prints 0 ... OMG
}
}

So, essentially, you are changing your comparison criteria on the fly, and that's just not the functionality that priority queue contracts offer. Note that this might seem to work on some cases (e.g. a heap might sort some of the items when removing or inserting another item) but since you have no guarantees, it's just not a valid approach.
What you could do is, every time you change your arrays, you get all the elements out, and put them back in. This is of course very expensive ( O(n*log(n))) so you should probably try to work around your design to avoid changing the array values at all.

Your comparator is only getting called when you modify the queue (that is, when you add your items). After that, the queue has no idea something caused the order to change, which is why it remains the same.
It is quite confusing to have a comparator like this. If you have two values, A and B, and A>B at some point, everybody would expect A to stay bigger than B. I think your usage of a priority queue for this problem is wrong.

Use custom implementation of PriorityQueue that uses comparator on peek, not on add:
public class VolatilePriorityQueue <T> extends AbstractQueue <T>
{
private final Comparator <? super T> comparator;
private final List <T> elements = new ArrayList <T> ();
public VolatilePriorityQueue (Comparator <? super T> comparator)
{
this.comparator = comparator;
}
#Override
public boolean offer (T e)
{
return elements.add (e);
}
#Override
public T poll ()
{
if (elements.isEmpty ()) return null;
else return elements.remove (getMinimumIndex ());
}
#Override
public T peek ()
{
if (elements.isEmpty ()) return null;
else return elements.get (getMinimumIndex ());
}
#Override
public Iterator <T> iterator ()
{
return elements.iterator ();
}
#Override
public int size ()
{
return elements.size ();
}
private int getMinimumIndex ()
{
T e = elements.get (0);
int index = 0;
for (int count = elements.size (), i = 1; i < count; i++)
{
T ee = elements.get (i);
if (comparator.compare (e, ee) > 0)
{
e = ee;
index = i;
}
}
return index;
}
}

Related

How can I sort a list based on another list values in Java [duplicate]

I've seen several other questions similiar to this one but I haven't really been able to find anything that resolves my problem.
My use case is this: user has a list of items initially (listA). They reorder the items and want to persist that order (listB), however, due to restrictions I'm unable persist the order on the backend so I have to sort listA after I retrieve it.
So basically, I have 2 ArrayLists (listA and listB). One with the specific order the lists should be in (listB) and the other has the list of items (listA). I want to sort listA based on listB.
Using Java 8:
Collections.sort(listToSort,
Comparator.comparing(item -> listWithOrder.indexOf(item)));
or better:
listToSort.sort(Comparator.comparingInt(listWithOrder::indexOf));
Collections.sort(listB, new Comparator<Item>() {
public int compare(Item left, Item right) {
return Integer.compare(listA.indexOf(left), listA.indexOf(right));
}
});
This is quite inefficient, though, and you should probably create a Map<Item, Integer> from listA to lookup the positions of the items faster.
Guava has a ready-to-use comparator for doing that: Ordering.explicit()
Let's say you have a listB list that defines the order in which you want to sort listA. This is just an example, but it demonstrates an order that is defined by a list, and not the natural order of the datatype:
List<String> listB = Arrays.asList("Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday");
Now, let's say that listA needs to be sorted according to this ordering. It's a List<Item>, and Item has a public String getWeekday() method.
Create a Map<String, Integer> that maps the values of everything in listB to something that can be sorted easily, such as the index, i.e. "Sunday" => 0, ..., "Saturday" => 6. This will provide a quick and easy lookup.
Map<String, Integer> weekdayOrder = new HashMap<String, Integer>();
for (int i = 0; i < listB.size(); i++)
{
String weekday = listB.get(i);
weekdayOrder.put(weekday, i);
}
Then you can create your custom Comparator<Item> that uses the Map to create an order:
public class ItemWeekdayComparator implements Comparator<Item>
{
private Map<String, Integer> sortOrder;
public ItemWeekdayComparator(Map<String, Integer> sortOrder)
{
this.sortOrder = sortOrder;
}
#Override
public int compare(Item i1, Item i2)
{
Integer weekdayPos1 = sortOrder.get(i1.getWeekday());
if (weekdayPos1 == null)
{
throw new IllegalArgumentException("Bad weekday encountered: " +
i1.getWeekday());
}
Integer weekdayPos2 = sortOrder.get(i2.getWeekday());
if (weekdayPos2 == null)
{
throw new IllegalArgumentException("Bad weekday encountered: " +
i2.getWeekday());
}
return weekdayPos1.compareTo(weekdayPos2);
}
}
Then you can sort listA using your custom Comparator.
Collections.sort(listA, new ItemWeekdayComparator(weekdayOrder));
Speed improvement on JB Nizet's answer (from the suggestion he made himself). With this method:
Sorting a 1000 items list 100 times improves speed 10 times on my
unit tests.
Sorting a 10000 items list 100 times improves speed 140 times (265 ms for the whole batch instead of 37 seconds) on my
unit tests.
This method will also work when both lists are not identical:
/**
* Sorts list objectsToOrder based on the order of orderedObjects.
*
* Make sure these objects have good equals() and hashCode() methods or
* that they reference the same objects.
*/
public static void sortList(List<?> objectsToOrder, List<?> orderedObjects) {
HashMap<Object, Integer> indexMap = new HashMap<>();
int index = 0;
for (Object object : orderedObjects) {
indexMap.put(object, index);
index++;
}
Collections.sort(objectsToOrder, new Comparator<Object>() {
public int compare(Object left, Object right) {
Integer leftIndex = indexMap.get(left);
Integer rightIndex = indexMap.get(right);
if (leftIndex == null) {
return -1;
}
if (rightIndex == null) {
return 1;
}
return Integer.compare(leftIndex, rightIndex);
}
});
}
Problem : sorting a list of Pojo on the basis of one of the field's all possible values present in another list.
Take a look at this solution, may be this is what you are trying to achieve:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Employee> listToSort = new ArrayList<>();
listToSort.add(new Employee("a", "age11"));
listToSort.add(new Employee("c", "age33"));
listToSort.add(new Employee("b", "age22"));
listToSort.add(new Employee("a", "age111"));
listToSort.add(new Employee("c", "age3"));
listToSort.add(new Employee("b", "age2"));
listToSort.add(new Employee("a", "age1"));
List<String> listWithOrder = new ArrayList<>();
listWithOrder.add("a");
listWithOrder.add("b");
listWithOrder.add("c");
Collections.sort(listToSort, Comparator.comparing(item ->
listWithOrder.indexOf(item.getName())));
System.out.println(listToSort);
}
}
class Employee {
String name;
String age;
public Employee(String name, String age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public String getAge() {
return age;
}
#Override
public String toString() {
return "[name=" + name + ", age=" + age + "]";
}
}
O U T P U T
[[name=a, age=age11], [name=a, age=age111], [name=a, age=age1], [name=b, age=age22], [name=b, age=age2], [name=c, age=age33], [name=c, age=age3]]
Here is a solution that increases the time complexity by 2n, but accomplishes what you want. It also doesn't care if the List R you want to sort contains Comparable elements so long as the other List L you use to sort them by is uniformly Comparable.
public class HeavyPair<L extends Comparable<L>, R> implements Comparable<HeavyPair<L, ?>> {
public final L left;
public final R right;
public HeavyPair(L left, R right) {
this.left = left;
this.right = right;
}
public compareTo(HeavyPair<L, ?> o) {
return this.left.compareTo(o.left);
}
public static <L extends Comparable<L>, R> List<R> sort(List<L> weights, List<R> toSort) {
assert(weights.size() == toSort.size());
List<R> output = new ArrayList<>(toSort.size());
List<HeavyPair<L, R>> workHorse = new ArrayList<>(toSort.size());
for(int i = 0; i < toSort.size(); i++) {
workHorse.add(new HeavyPair(weights.get(i), toSort.get(i)))
}
Collections.sort(workHorse);
for(int i = 0; i < workHorse.size(); i++) {
output.add(workHorse.get(i).right);
}
return output;
}
}
Excuse any terrible practices I used while writing this code, though. I was in a rush.
Just call HeavyPair.sort(listB, listA);
Edit: Fixed this line return this.left.compareTo(o.left);. Now it actually works.
Here is an example of how to sort a list and then make the changes in another list according to the changes exactly made to first array list. This trick will never fails and ensures the mapping between the items in list. The size of both list must be same to use this trick.
ArrayList<String> listA = new ArrayList<String>();
ArrayList<String> listB = new ArrayList<String>();
int j = 0;
// list of returns of the compare method which will be used to manipulate
// the another comparator according to the sorting of previous listA
ArrayList<Integer> sortingMethodReturns = new ArrayList<Integer>();
public void addItemstoLists() {
listA.add("Value of Z");
listA.add("Value of C");
listA.add("Value of F");
listA.add("Value of A");
listA.add("Value of Y");
listB.add("this is the value of Z");
listB.add("this is the value off C");
listB.add("this is the value off F");
listB.add("this is the value off A");
listB.add("this is the value off Y");
Collections.sort(listA, new Comparator<String>() {
#Override
public int compare(String lhs, String rhs) {
// TODO Auto-generated method stub
int returning = lhs.compareTo(rhs);
sortingMethodReturns.add(returning);
return returning;
}
});
// now sort the list B according to the changes made with the order of
// items in listA
Collections.sort(listB, new Comparator<String>() {
#Override
public int compare(String lhs, String rhs) {
// TODO Auto-generated method stub
// comparator method will sort the second list also according to
// the changes made with list a
int returning = sortingMethodReturns.get(j);
j++;
return returning;
}
});
}
try this for java 8:
listB.sort((left, right) -> Integer.compare(list.indexOf(left), list.indexOf(right)));
or
listB.sort(Comparator.comparingInt(item -> list.indexOf(item)));
import java.util.Comparator;
import java.util.List;
public class ListComparator implements Comparator<String> {
private final List<String> orderedList;
private boolean appendFirst;
public ListComparator(List<String> orderedList, boolean appendFirst) {
this.orderedList = orderedList;
this.appendFirst = appendFirst;
}
#Override
public int compare(String o1, String o2) {
if (orderedList.contains(o1) && orderedList.contains(o2))
return orderedList.indexOf(o1) - orderedList.indexOf(o2);
else if (orderedList.contains(o1))
return (appendFirst) ? 1 : -1;
else if (orderedList.contains(o2))
return (appendFirst) ? -1 : 1;
return 0;
}
}
You can use this generic comparator to sort list based on the the other list.
For example, when appendFirst is false below will be the output.
Ordered list: [a, b]
Un-ordered List: [d, a, b, c, e]
Output:
[a, b, d, c, e]
One way of doing this is looping through listB and adding the items to a temporary list if listA contains them:
List<?> tempList = new ArrayList<?>();
for(Object o : listB) {
if(listA.contains(o)) {
tempList.add(o);
}
}
listA.removeAll(listB);
tempList.addAll(listA);
return tempList;
Not completely clear what you want, but if this is the situation:
A:[c,b,a]
B:[2,1,0]
And you want to load them both and then produce:
C:[a,b,c]
Then maybe this?
List c = new ArrayList(b.size());
for(int i=0;i<b.size();i++) {
c.set(b.get(i),a.get(i));
}
that requires an extra copy, but I think to to it in place is a lot less efficient, and all kinds of not clear:
for(int i=0;i<b.size();i++){
int from = b.get(i);
if(from == i) continue;
T tmp = a.get(i);
a.set(i,a.get(from));
a.set(from,tmp);
b.set(b.lastIndexOf(i),from);
}
Note I didn't test either, maybe got a sign flipped.
Another solution that may work depending on your setting is not storing instances in listB but instead indices from listA. This could be done by wrapping listA inside a custom sorted list like so:
public static class SortedDependingList<E> extends AbstractList<E> implements List<E>{
private final List<E> dependingList;
private final List<Integer> indices;
public SortedDependingList(List<E> dependingList) {
super();
this.dependingList = dependingList;
indices = new ArrayList<>();
}
#Override
public boolean add(E e) {
int index = dependingList.indexOf(e);
if (index != -1) {
return addSorted(index);
}
return false;
}
/**
* Adds to this list the element of the depending list at the given
* original index.
* #param index The index of the element to add.
*
*/
public boolean addByIndex(int index){
if (index < 0 || index >= this.dependingList.size()) {
throw new IllegalArgumentException();
}
return addSorted(index);
}
/**
* Returns true if this list contains the element at the
* index of the depending list.
*/
public boolean containsIndex(int index){
int i = Collections.binarySearch(indices, index);
return i >= 0;
}
private boolean addSorted(int index){
int insertIndex = Collections.binarySearch(indices, index);
if (insertIndex < 0){
insertIndex = -insertIndex-1;
this.indices.add(insertIndex, index);
return true;
}
return false;
}
#Override
public E get(int index) {
return dependingList.get(indices.get(index));
}
#Override
public int size() {
return indices.size();
}
}
Then you can use this custom list as follows:
public static void main(String[] args) {
class SomeClass{
int index;
public SomeClass(int index) {
super();
this.index = index;
}
#Override
public String toString() {
return ""+index;
}
}
List<SomeClass> listA = new ArrayList<>();
for (int i = 0; i < 100; i++) {
listA.add(new SomeClass(i));
}
SortedDependingList<SomeClass> listB = new SortedDependingList<>(listA);
Random rand = new Random();
// add elements by index:
for (int i = 0; i < 5; i++) {
int index = rand.nextInt(listA.size());
listB.addByIndex(index);
}
System.out.println(listB);
// add elements by identity:
for (int i = 0; i < 5; i++) {
int index = rand.nextInt(listA.size());
SomeClass o = listA.get(index);
listB.add(o);
}
System.out.println(listB);
}
Of course, this custom list will only be valid as long as the elements in the original list do not change. If changes are possible, you would need to somehow listen for changes to the original list and update the indices inside the custom list.
Note also, that the SortedDependingList does currently not allow to add an element from listA a second time - in this respect it actually works like a set of elements from listA because this is usually what you want in such a setting.
The preferred way to add something to SortedDependingList is by already knowing the index of an element and adding it by calling sortedList.addByIndex(index);
If the two lists are guaranteed to contain the same elements, just in a different order, you can use List<T> listA = new ArrayList<>(listB) and this will be O(n) time complexity. Otherwise, I see a lot of answers here using Collections.sort(), however there is an alternative method which is guaranteed O(2n) runtime, which should theoretically be faster than sort's worst time complexity of O(nlog(n)), at the cost of 2n storage
Set<T> validItems = new HashSet<>(listB);
listA.clear();
listB.forEach(item -> {
if(validItems.contains(item)) {
listA.add(item);
}
});
List<String> listA;
Comparator<B> comparator = Comparator.comparing(e -> listA.indexOf(e.getValue()));
//call your comparator inside your list to be sorted
listB.stream().sorted(comparator)..
Like Tim Herold wrote, if the object references should be the same, you can just copy listB to listA, either:
listA = new ArrayList(listB);
Or this if you don't want to change the List that listA refers to:
listA.clear();
listA.addAll(listB);
If the references are not the same but there is some equivalence relationship between objects in listA and listB, you could sort listA using a custom Comparator that finds the object in listB and uses its index in listB as the sort key. The naive implementation that brute force searches listB would not be the best performance-wise, but would be functionally sufficient.
IMO, you need to persist something else. May be not the full listB, but something. May be just the indexes of the items that the user changed.
Try this. The code below is general purpose for a scenario where listA is a list of Objects since you did not indicate a particular type.
Object[] orderedArray = new Object[listA.size()];
for(int index = 0; index < listB.size(); index ++){
int position = listB.get(index); //this may have to be cast as an int
orderedArray[position] = listA.get(index);
}
//if you receive UnsupportedOperationException when running listA.clear()
//you should replace the line with listA = new List<Object>()
//using your actual implementation of the List interface
listA.clear();
listA.addAll(orderedArray);
Just encountered the same problem.
I have a list of ordered keys, and I need to order the objects in a list according to the order of the keys.
My lists are long enough to make the solutions with time complexity of N^2 unusable.
My solution:
<K, T> List<T> sortByOrder(List<K> orderedKeys, List<T> objectsToOrder, Function<T, K> keyExtractor) {
AtomicInteger ind = new AtomicInteger(0);
Map<K, Integer> keyToIndex = orderedKeys.stream().collect(Collectors.toMap(k -> k, k -> ind.getAndIncrement(), (oldK, newK) -> oldK));
SortedMap<Integer, T> indexToObj = new TreeMap<>();
objectsToOrder.forEach(obj -> indexToObj.put(keyToIndex.get(keyExtractor.apply(obj)), obj));
return new ArrayList<>(indexToObj.values());
}
The time complexity is O(N * Log(N)).
The solution assumes that all the objects in the list to sort have distinct keys. If not then just replace SortedMap<Integer, T> indexToObj by SortedMap<Integer, List<T>> indexToObjList.
To avoid having a very inefficient look up, you should index the items in listB and then sort listA based on it.
Map<Item, Integer> index = IntStream.range(0, listB.size()).boxed()
.collect(Collectors.toMap(listB::get, x -> x));
listA.sort((e1, e2) -> Integer.compare(index.get(c1), index.get(c2));
So for me the requirement was to sort originalList with orderedList. originalList always contains all element from orderedList, but not vice versa. No new elements.
fun <T> List<T>.sort(orderedList: List<T>): List<T> {
return if (size == orderedList.size) {
orderedList
} else {
var keepIndexCount = 0
mapIndexed { index, item ->
if (orderedList.contains(item)) {
orderedList[index - keepIndexCount]
} else {
keepIndexCount++
item
}
}
}}
P.S. my case was that I have list that user can sort by drag and drop, but some items might be filtered out, so we preserve hidden items position.
If you want to do it manually. Solution based on bubble sort (same length required):
public void sortAbasedOnB(String[] listA, double[] listB) {
for (int i = 0; i < listB.length - 1; i++) {
for (int j = listB.length - 1; j > i; j--) {
if (listB[j] < listB[j - 1]){
double tempD = listB[j - 1];
listB[j - 1] = listB[j];
listB[j] = tempD;
String tempS = listA[j - 1];
listA[j - 1] = listA[j];
listA[j] = tempS;
}
}
}
}
If the object references should be the same, you can initialize listA new.
listA = new ArrayList(listB)
In Java there are set of classes which can be useful to sort lists or arrays. Most of the following examples will use lists but the same concept can be applied for arrays. A example will show this.
We can use this by creating a list of Integers and sort these using the Collections.sort(). The Collections (Java Doc) class (part of the Java Collection Framework) provides a list of static methods which we can use when working with collections such as list, set and the like. So in a nutshell, we can sort a list by simply calling: java.util.Collections.sort(the list) as shown in the following example:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class example {
public static void main(String[] args) {
List<Integer> ints = new ArrayList<Integer>();
ints.add(4);
ints.add(3);
ints.add(7);
ints.add(5);
Collections.sort(ints);
System.out.println(ints);
}
}
The above class creates a list of four integers and, using the collection sort method, sorts this list (in one line of code) without us having to worry about the sorting algorithm.

Abstract Data Type implementation in Procedural Programming

I have a question for the more advanced OOP developers here.
I am currently a CS student. We learned a Procedural Programming in Java the first semester where ADT was introduced. I understand the theory and the idea of why ADT is good and what are the benefits of it but it seems quite difficult for me to implement it in code. I get confused and lost.
In addition to that our exit test was on paper (we had to write around 200 line of code on paper) and I found it difficult.
Are there any tips before starting to construct the program?
For instance, do you guys already know how many methods and what method what it will return and have as a formal argument before you start to write the code?
You can approach it programming-style.
First, you need to define an interface for the ADT. Just write down its name and what it does.
Example:
ADT: Integer Stack
void push(int element) - adds an element to the top of stack
int pop() - removes and returns an element from the top of stack
int peek() - returns the value of top. no removal of value
boolean isEmpty() - returns true if the stack is empty
int size() - returns the number of element in the stack.
void print() - print all values of stack
Next is you need to decide on its implementation. Since ADT is about storage, it will be good to decide on storage strategy first.
Example:
ADT: Integer Stack
Implementation: Array Integer Stack
Implements an int stack using Java's built-in array functionality.
Since array is a static collection, i need to use an integer variable to track "top"
When everything is set, you can now proceed to coding.
public interface IntegerStack {
void push(int e);
int pop();
int peek();
boolean isEmpty();
int size();
void print();
}
public class ArrayIntegerStack implements IntegerStack {
private static final int INITIAL_TOP_INDEX = -1;
private int topIndex = INITIAL_TOP_INDEX;
private int[] stackValue = new int[Integer.MAX_VALUE];
#Override
public void push(int element) {
stackValue[++topIndex] = element;
}
#Override
public int pop() {
return stackValue[topIndex--];
}
#Override
public int peek() {
return stackValue[topIndex];
}
#Override
public boolean isEmpty() {
return INITIAL_TOP_INDEX == topIndex;
}
#Override
public int size() {
return topIndex + 1;
}
#Override
public void print() {
for (int i = 0; i <= topIndex; i++) {
System.out.println(stackValue[i]);
}
}
}
Adding on to the answer of KaNa001, you could use a modified HashMap where the key is the index and the value is the integer in the stack. This wont cause an Exception, as the HashMap object can change its length.
public class OrderSet<T> {
private HashMap<Integer, T> array;
public OrderSet() {
array = new HashMap<Integer, T>();
}
public void addAt (T o, int pos) {
// uses Array indexing
HashMap<Integer, T> temp = new HashMap<Integer, T>();
if (!(array.size() == 0)) {
for (int i = 0; i < array.size(); i++) {
temp.put(i, array.get(i));
}
array.put(pos, o);
int size = array.size();
for (int i = pos + 1; i < size + 1; i++) {
array.put(i, temp.get(i - 1));
}
} else {
array.put(0, o);
}
}
public T getPos (int pos) {
if (array.size() == 0) {
return null;
} else {
return array.get(pos);
}
}
}

How to create high priority bounded subqueue and low priority bounded subqueue in JAVA

I have created a priority queue and filled the queue with items and using this queue as basis I iterated through it and found the priority of the items. Depending on the priority am moving items to subqueues using some logic.
In my main program I created bounded subqueues using static statements what I would like to do is create the bounded subqueue using the constructor of my parent queue Constructor: public HiLoPriorityQueue(int high_capacity, int low_capacity)
the constructor should create high priority bounded sub-queue with initial capacity high_capacity and a low priority bounded sub-queue with capacity low_capacity
Can the subqueues be created from parent queue by using the same add and remove methods applied on the parent queue??
My Main Program:
public class PQTest {
public static void main(String[] args) {
HiLoPriorityQueue<Customer> prq = new HiLoPriorityQueue<Customer>(10);
Customer c1 = new Customer("Rock",999);
Customer c2 = new Customer("Brock",1);
Customer c3 = new Customer("UnderTaker",1000);
HiLoPriorityQueue<Customer> hq = new HiLoPriorityQueue<Customer>(5);
HiLoPriorityQueue<Customer> lq = new HiLoPriorityQueue<Customer>(3);
// insert values in the queue
prq.add(c1);
prq.add(c2);
prq.add(c3);
// create iterator from the queue
Iterator it = prq.iterator();
System.out.println ( "Priority queue values are: ");
while (it.hasNext()){
Customer c = (Customer) it.next();
System.out.println ( "Value: "+ c);
System.out.println("Priority is :: "+c.getPriority());
if(c.getPriority() == 1){
if(hq.size() < 5 )
hq.add(c);
else{
if(hq.size() < 5 ) lq.add(c);
else{
lq.remove();
lq.add(c);
}
}
}
else{
if(lq.size() < 3) lq.add(c);
}
}
}
}
Queue creation class:
public class HiLoPriorityQueue<E extends BinaryPrioritizable> extends AbstractCollection{
private int count;
private Object[] elements;
private Object[] helements;
private Object[] lelements;
private int head;
private int tail;
public HiLoPriorityQueue(int high_capacity, int low_capacity){
helements = new Object[high_capacity];
lelements = new Object[low_capacity];
count = 0;
head = 0;
tail = 0;
}
public HiLoPriorityQueue(int capacity)
{
elements = new Object[capacity];
count = 0;
head = 0;
tail = 0;
}
#Override
public Iterator<E> iterator()
{
return new Iterator<E>()
{
public boolean hasNext()
{
return visited < count;
}
public E next()
{
int index = (head + visited) % elements.length;
E r = (E) elements[index];
visited++;
return r;
}
public void remove()
{
throw new UnsupportedOperationException();
}
private int visited = 0;
};
}
public boolean add(E anObject)
{
elements[tail] = anObject;
tail = (tail + 1) % elements.length;
count++;
return true;
}
public E remove()
{
E r = (E) elements[head];
head = (head + 1) % elements.length;
count--;
return r;
}
#Override
public int size()
{
return count;
}
}
Your code makes little sense. Why are you using Object[] arrays to hold your elements in your HiLoPriorityQueue class? Using a Object array is generally a bad idea and I think it would make more sense to use ArrayList<E extends BinaryPrioritizable> as per your class specification. Secondly, why do you have helements and lelements since they are never being used?
Can the subqueues be created from parent queue by using the same add and remove methods applied on the parent queue??
The answer to this question yes, since your parent queue is the same type as your sub-queues. But I'm not entirely sure if this is what you're asking or not, neither am I entirely sure what you're trying to do.
If I've understood you correctly, however, I think you're trying to keep a low priority queue and a high priority queue. These should go inside your HiLoPriorityQueue class and be handled internally whenever a user adds/removes data. Your priority separation logic should go inside the add() method of your HiLoPriorityQueue class.
Finally, if you want a data structure such that all high-priority elements are handled before the low priority elements you should just use a built in MaxHeap (i.e PirorityQueue<Customer> q = new PriorityQueue<Customer>()) where you specify a comparator.
Hope this helps.

Sorting algorithms - how to implement my classes in main :)

It's silly problem. I have my own comparator interface, class Student - it's objects will be sorted, class BubbleSort with bubblesorting algorithm and main. I think every class except from main is written quite well, but I have problem with implementation of them in main to make my sorting to start :/ I've just created ArrayList of random Students I want to be sorted, but I have problem with BubbleSort class and have no idea, how to start.
In future (I hope it will be today :)) I will do exactly the same with another classes containing sorting algorithms like BubbleSort here. I think their implementation in main will be identical.
import java.util.Random;
import java.util.ArrayList;
public class Program {
public static void main(String[] args) {
int elements = 100000;
ArrayList<Student> list = new ArrayList<Student>();
Random rand = new Random();
for (int i=0; i<elements; i++) {
list.add(new Student(rand.nextInt(4)+2, rand.nextInt(900000)));
}
System.out.println(list);
}
}
.
import java.util.ArrayList;
public class BubbleSort {
private final Comparator comparator;
public BubbleSort(Comparator comparator) {
this.comparator = comparator;
}
public ArrayList<Student> sort(ArrayList<Student> list) {
int size = list.size();
for (int pass = 1; pass < size; ++pass) {
for (int left = 0; left < (size - pass); ++left) {
int right = left + 1;
if (comparator.compare(list.get(left), list.get(right)) > 0)
swap(list, left, right);
}
}
return list;
}
public int compare(Object left, Object right) throws ClassCastException
{ return comparator.compare(left, right); }
private void swap(ArrayList list, int left, int right) {
Object temp = list.get(left);
list.set(left, list.get(right));
list.set(right, temp);
}
}
.
public class Student implements Comparator<Student> {
int rate;
int indeks;
public Student(int ocena, int index) {
this.rate = ocena;
indeks = index;
}
public String toString() {
return "Numer indeksu: " + indeks + " ocena: " + rate + "\n";
}
public int getIndeks() {
return indeks;
}
public int getRate() {
return rate;
}
public int compare(Student left, Student right) {
if (left.getIndeks()<right.getIndeks()) {
return -1;
}
if (left.getIndeks() == right.getIndeks()) {
return 0;
}
else {
return 1;
}
}
}
.
public interface Comparator<T> {
public int compare(T left, T right) throws ClassCastException;
}
Your code looks little bit strange. You didnt mention if you have to use bubble sort so i write both my ideas
1.Without explicitly using bubble sort
You can use Collections.sort() combined with overridencompareTo() method
So your code will look like this
class Student implements Comparable<Student>{
//variables constructor methods go here
private index;
#Override
public int compareTo(Students s) {
int index = s.index;
if (this.index > index) {
return 1;
} else if (this.index == index) {
return 0;
} else {
return -1;
}
}
}
And in your main class Collections.sort(myStudents)
2.Explicitly using bubble sort
Student class
class Student{
//class variables methods constructor goes here
}
Comparator class
class StudentComparator implements Comparator<Student>{
#Override
public int compare(Student a, Student b) {
//bubble sort code goes here
}}
Main class
class MyMainClass{
public static void main(String[] args) {
public int elements = 100000;
ArrayList<Student> list = new ArrayList<Student>();
Random rand = new Random();
for (int i=0; i<elements; i++) {
list.add(new Student(rand.nextInt(4)+2, rand.nextInt(900000)));
}
Collections.sort(list, new StudentComparator());
}
Two points to make here:
a) You are not calling sort at all. You need to instantiate your BubbleSort class and actually call the method. list = new BubbleSort(new Comparator(){...}).sort(list); <-- This syntax also calls for the sort method to be static so that you don't need to make a new object for every sort. The example below sorts by index.
list = new BubbleSort(new Comparator<Student>() {
#Override
public compare(Student a, Student b) {
return a.getIndeks() - b.getIndeks();
}
}).sort(list);
Btw, this also assumes that BubbleSort is made generic, since it's easier (and kinda makes sense anyway)
b) I hope this is some kind of project where you have to show your ability to make a sorting algorithm, otherwise you should use library methods for these things
Also, while the code is not bad, you might want to show it to someone with professional Java experience (it does not conform to a lot of standards and many things can be improved and made consistent with each other), or post it to https://codereview.stackexchange.com/
I dont see you calling the bubblesort class anywhere. A list will not automatically sort its elements. Please go through this link. You ll find it handy.
http://www.programcreek.com/2013/03/hashset-vs-treeset-vs-linkedhashset/

compareTo with generics for heapSort

For class I had to either implement a BST or a heapSort. I did the BST but figured it would be good to know this too but now I'm stuck. This is my first time working with heaps(and really coding with generics/implementing Comparable so I apologize for all the errors) and im running into an issue implementing compareTo.
Essentially I want to be able to add generic objects to my heap Array and then compare them for the Heap sorting. I use compareTo to check a new entry when adding to the heap and for swapping in the reheap method.
My errors returned:
Heap.java:64: error: bad operand types for binary operator '<'
if (this < other)
^
first type: Heap<T>
second type: Heap<T>
where T is a type-variable:
T extends Comparable<T> declared in class Heap
Im not sure how to work around that though. I understand that my binary operator isnt for generics but I dont know how to work around it.
Thanks for any input. Sorry about all the beginners mistakes you may find!
Heres my code:
import java.util.*;
class Heap<T extends Comparable <T>> implements Comparable<Heap<T>>{
private T[] heap;
private int lastIndex;
private static final int CAPACITY = 25;
public Heap(){
this(CAPACITY);
}
public Heap(int capacity){
heap = (T[])new Comparable[capacity+1];
lastIndex = 0;
}
public void add(T newEntry){
lastIndex++;
if(lastIndex>=heap.length)
doubleArray();
int newIndex = lastIndex;
int parentIndex = newIndex/2;
while((parentIndex>0)&&(heap[parentIndex].compareTo(newEntry)>0))
{
heap[newIndex] = heap[parentIndex];
newIndex = parentIndex;
parentIndex = newIndex/2;
}
heap[newIndex] = newEntry;
}
public void display()
{
for(int i=1;i<heap.length;i++)
{
System.out.println(heap[i]);
}
}
private void doubleArray()
{
T[] oldHeap = heap;
int oldSize = heap.length;
heap = (T[]) new Object[2*oldSize];
for(int i =0; i < oldSize-1;i++)
{
heap[i] = oldHeap[i];
}
}
public int compareTo(Heap<T> other)
{
int sort = 0;
if (this < other)
{
sort = -1;
}
else if (this> other)
{
sort = 1;
}
else
{
sort = 0;
}
return sort;
}
private <T extends Comparable<T>> void reheap(T[] heap, int rootIndex, int lastIndex)
{
boolean done=false;
T orphan = heap[rootIndex];
int leftChildIndex = 2 * rootIndex + 1;
while(!done && (leftChildIndex<=lastIndex))
{
int largerChildIndex = leftChildIndex;
int rightChildIndex = leftChildIndex + 1;
if(rightChildIndex<=lastIndex && (heap[rightChildIndex].compareTo(heap[largerChildIndex])>0))
largerChildIndex = rightChildIndex;
if(orphan.compareTo(heap[largerChildIndex])<0)
{
// System.out.println(orphan+ "--" + largerChildIndex);
heap[rootIndex] = heap[largerChildIndex];
rootIndex = largerChildIndex;
leftChildIndex = 2 * rootIndex+1;
}
else
done = true;
}
heap[rootIndex] = orphan;
}
public <T extends Comparable<T>> void heapSort(int n)
{
for(int rootIndex = n/2-1;rootIndex >=0;rootIndex--)
reheap(heap,rootIndex,n-1);
swap(heap,0,n-1);
for(int lastIndex = n-2;lastIndex > 0;lastIndex--)
{
reheap(heap,0,lastIndex);
swap(heap,0,lastIndex);
}
}
private <T extends Comparable<T>> void swap(T[] a,int first, int last)
{
T temp;
temp = a[first];
a[first] = a[last];
a[last] = temp;
}
}
Any help with any of this is very very appreciated
You don't want your heap to be Comparable; you want to compare its members. Therefore remove implements Comparable<Heap<T>> from your class declaration and remove the compareTo method.
Many of your methods (reheap, heapSort, swap) redundantly declare <T extends Comparable<T>> where you are already in the context of your class parameterized with T. Remove those declarations.
I think you need to implement the compareTo on you T object, not on the heap itself. You have to
make sure T is comparable for it to be in the heap.

Categories