开发者

How can i use Comparator to implement Bubble sort?

开发者 https://www.devze.com 2023-02-25 16:12 出处:网络
How can i implement Bubble sort by using Comparator? Thank you. This is how my comparator looks: class ColumnSorter implements Comparator {

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 && ((S开发者_如何学JAVAtring) 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());
 }
}
}


You implement bubble sort just as you would with, say <. Then you replace the use of < with someComparator.compare(Object o1, Object o2).

Here's the "translation rule":

if (arr[i] < arr[j]) {
    ...
}

becomes

if (someComparator.compare(arr[i], arr[j]) < 0) {
    ...
}

(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:

Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.


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 a Comparator, or one without that uses the natural ordering of objects (if they implement the Comparable interface).

0

精彩评论

暂无评论...
验证码 换一张
取 消