gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:34:26 24 4
gpt4 key购买 nike

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

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 - 使用 Comparable 在 Java 中进行快速排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6944345/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com