How can i implement Bubble sort by using Comparator?
Thank you.
This is how my comparator looks:
class ColumnSorter implements Comparator {
int colIndex;
ColumnSorter(int colIndex) {
this.colIndex = colIndex;
}
public int compare(Object a, Object b) {
Vector v1 = (Vector) a;
Vector v2 = (Vector) b;
Object o1 = v1.get(colIndex);
Object o2 = v2.get(colIndex);
if (o1 instanceof String && ((String) o1).length() == 0) {
o1 = null;
}
if (o2 instanceof String && ((String) o2).length() == 0) {
o2 = null;
}
if (o1 == null && o2 == null) {
return 0;
} else if (o1 == null) {
return 1;
} else if (o2 == null) {
return -1;
} else if (o1 instanceof Comparable) {
return ((Comparable) o1).compareTo(o2);
} else {
return o1.toString().compareTo(o2.toString());
}
}
}
I'll assume you know how to code a Bubble Sort and that the problem is how to use a Comparator.
At every iteration in the bubble sort you have to compare two items to decide which order they should be in. Where you would say:
if item1 < item2 then
you now write:
if( comparator.compare(item1,item2) < 0 ) {
If you would say:
if item1 > item2 then
then you write
if( comparator.compare(item1,item2) > 0 ) {
Note that the
<
and>
remain the same and you keep the order of the items the same. If you stick to that rule the comparison should work fine, so all that is left is the actual bubble sort.The big question is why on earth you would want to implement a bubble sort by yourself. Bubble sort is one of the slowest sorting algorithms around.
Using the sorting algorithm provided by the JDK in
java.util.Collections.sort()
would be much faster and save you quite some lines of code.Collections.sort()
has a method that takes aComparator
, or one without that uses the natural ordering of objects (if they implement theComparable
interface).You implement bubble sort just as you would with, say
<
. Then you replace the use of<
withsomeComparator.compare(Object o1, Object o2)
.Here's the "translation rule":
becomes
(If you used
>
, you would use> 0
instead of< 0
.)You should consult the documentation for
Comparator
for further details. Here's the first sentence: