I have a bubble sort function that orders LinkedList of SomeObj by “a” variable. What if i want to order the list by “b” variable at the same time? What can i do instead of writing another function with b?
public static void BubbleSort(LinkedList<SomeObj> objs) {
int len = objs.size();
for(int pass = 1; pass < len; pass++) {
for (int i=0; i < len - pass; i++) {
if(objs.get(i).a > objs.get(i + 1).a) {
SomeObj p = objs.get(i);
objs.set(i,objs.get(i+1));
objs.set(i + 1, p);
}
}
}
}
Implement Comparator interface in a class with its compare method.
that accepts two objects and compares them which returns -ve,0,+ve values to tell less than , equal or greater than.
create an object of this Comparator and pass it to bubble sort method and let it use its compare method to compare the two object.
Your object should have getters for all such fields.
Also whenever you wanna change the object’s criteria for comparison , use a different Comparator.
Check this example.