Hi, I'm having some trouble writing a method to sort a LinkedQueue ADT. I find it difficult to keep track of the order things when sorting is concerned (ha ha ha).
I'm trying to pull the values out of a Queue which store objects of type PrinterItem. Those objects in turn each store two variables jobNumber (each of which is a unique integer value) and numPages (as well as a third variable that isn't relevant).
I am trying to sort the objects from least to greatest numPages value and if any two objects have the same numPages value then sort then from least to greatest jobNumber.
Here is the relevant code (which doesn't work). Note: the pass() method in this code merely takes in the object and returns it ensuring it has been properly cast.
sort method:
LinkedQueue<PrinterItem> tempQueue = new LinkedQueue();
while (!(obj.isEmpty())) {
PrinterItem firstSeen = pass(obj.dequeue());
if (obj.size() != 0) {
if ((pass(obj.first())).compareTo(firstSeen) == 1) {/*
* Swap items
*/
if (obj.size() != 0) {
PrinterItem secondSeen = pass(obj.dequeue());
tempQueue.enqueue(firstSeen);
tempQueue.enqueue(secondSeen);
}
} else if ((pass(obj.first())).compareTo(firstSeen) == -1) {/*
* replace dequed item
*/
if (obj.size() != 0) {
tempQueue.enqueue(firstSeen);
}
} else if ((pass(obj.first())).compareTo(firstSeen) == 0) {/*
* do nothing
*/
}
}
}
return tempQueue;
}
and the compareTo method in the PrintItem class is:
@Override
public int compareTo(PrinterItem o) {
int returnIt=0;
if (this.numPages < o.numPages) {
returnIt=-1;
} else if (this.numPages > o.numPages) {
returnIt=1;
} else if (this.numPages == o.numPages) {
if (this.jobNumber < o.jobNumber) {
returnIt=-1;
} else if (this.jobNumber > o.jobNumber) {
returnIt=1;
} else {
returnIt=0;
}
}
return returnIt;
}