我被要求改进给定的快速排序算法:
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;
}