如何使用比较器来实现冒泡排序? [英] How can i use Comparator to implement Bubble sort?

查看:134
本文介绍了如何使用比较器来实现冒泡排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用比较器实现气泡排序?

How can i implement Bubble sort by using Comparator?

谢谢。

这就是我的方式比较器看起来是:

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());
 }
}
}


推荐答案

您可以像执行< 一样实现气泡排序。然后将< 的使用替换为 someComparator.compare(Object o1,Object o2)

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

以下是翻译规则:

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

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

(如果使用> ,则应使用> 0 而不是< 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.

这篇关于如何使用比较器来实现冒泡排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆