java - Java中使用Comparable进行快速排序

标签 java quicksort comparable

我被要求改进给定的快速排序算法:

public void quickSort(Comparable[] a, int left, int right) {
// Sort a[left…right] into ascending order.
    if (left < right) {
        int p = partition(a, left, right);
        quickSort(a, left, p-1);
        quickSort(a, p+1, right);   
    }
}    




public int partition(Comparable[] a, int left, int right) {
// Partition a[left…right] such that  
// a[left…p-1] are all less than or equal to a[p] 
// and a[p+1…right] are all greater than or equal to 
// a[p]. Return p.
    Comparable pivot = a[left];
    int p = left;
    for (int r = left+1; r <= right; r++) {
        int comp = a[r].compareTo(pivot);
        if (comp < 0) {
            a[p] = a[r];  a[r] = a[p+1];
            a[p+1] = pivot;  p++;
        }
    }
    return p;
}

...使用下面的伪代码指令,因此它可以使用比初始算法更少的副本数来工作:

To partition a[left…right] such that a[left…j–1] are all less than or equal to a[j], 
and a[j+1…right] are all greater than or equal to a[j]:
1.  Set pivot to a[left].
2.  Set i = left + 1 and j = right.
3.  While i <= j, repeat:
    3.1.    While i <= j and a[i] <= pivot, increment i. 
    3.2.    While j >= i and a[j] >= pivot, decrement j.
    3.3.    If i < j, swap a[i] and a[j].
4.  If j != left, set a[left] to a[j], and a[j] to pivot. 
5.  Terminate with answer j.

问题是我无法解决这一点:

While i <= j and a[i] <= pivot,

因为我收到错误消息,指出我无法将 < 和 > 符号与 Comparable 一起使用。我在网上找到了一些解决方案,但没有一个有效。

有什么想法吗? 我真的很感激快速的线索,因为我没有时间来完成这个项目。

谢谢! 马塞潘

版本后的代码:

public int partition(Comparable[] a, int left, int right) {
 // Partition a[left…right] such that

 // a[left…p-1] are all less than or equal to a[p]

 // and a[p+1…right] are all greater than or equal to

 // a[p]. Return p.

 Comparable pivot = a[left];
 int i = left +1;
 int j = right;
 while (i<=j){
     while (i<=j && a[i].compareTo(pivot) <= 0){
         i++;
     }
     while (i>=j && a[j].compareTo(pivot) >= 0){
         j--;
     }
     if (i<j){
     a[i] = a[j];
     }
 }
 if ( j != left){
 a[left] = a[j];
 a[j] = pivot;
 }

 return j;

}

最佳答案

而不是 a < b ,你写 a.compareTo(b) < 0 .

其他比较运算符的写法类似,所以

a[i] <= pivot

变成

a[i].compareTo(pivot) <= 0

关于java - Java中使用Comparable进行快速排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6944345/

相关文章:

java - 我应该使用什么来实现 GWT 中的列表功能

java - 在MVC模型中以JSON格式显示查询结果

Python QuickSort 仅部分排序

java - 用Java实现自定义快速排序算法

java - 在实现 Comparable 接口(interface)的类中调用 collections.sort() 方法时引用的当前对象是什么?

java - 在 Comparable <Type> 类中实现 compareTo 时,特定的有符号整数是否重要?

java - 如何从java中的s3获取触发lambda的文件名

java - 我的 servlet-mapping 直接匹配默认 servlet

c - C中使用多线程的快速排序中的并行排序

java - 比较其他类的对象