使用Comparable在Java中进行快速排序

使用Comparable在Java中进行快速排序,java,quicksort,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,

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

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;
}
。。。使用下面的psude代码说明,使其能够使用比初始算法更少的拷贝数工作:

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,
因为我收到错误消息,说我不能使用具有可比性的<和>符号。我在网上找到的解决方案很少,但都不管用

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

谢谢! 马尔塞潘

版本后代码:

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 其他比较运算符的编写方式类似,因此

a[i] <= pivot
变成

a[i].compareTo(pivot) <= 0
您需要在可比上使用该方法:


所以a我将使用与您编写的代码相同的代码

int comp = a[r].compareTo(pivot);
if (comp < 0) {

它们是可比较的对象,所以你不能使用它,如果它是家庭作业,你应该给它贴上这样的标签。好吧,很难称之为家庭作业,更像是某种训练。不过我会记下来的,因为我是按照老师的命令来做的。在你的建议之后,我已经设法写了我添加到第一篇文章中的代码。尽管并没有语法错误,但程序不会编译并挂起。进一步的建议?@Marcepan:我只是粗略地看了一下你的代码,但是你可能想仔细检查一下while>=j&&a[j]。compareTopivot>=0,想想交换a[I]和a[j]到底意味着什么。哦,我检查了while语句,在做了一些小的修改之后,算法就完美地工作了!谢谢
while i <= j and ( a[i].compareTo(pivot) <= 0 )