消除快速排序算法的边界-JAVA
在下面代码的分区方法中,如何删除内部while循环中的两个边界检查 我知道第二个while循环是多余的,因为[lo]充当哨兵,但简单地删除它似乎不起作用消除快速排序算法的边界-JAVA,java,algorithm,quicksort,bounds,Java,Algorithm,Quicksort,Bounds,在下面代码的分区方法中,如何删除内部while循环中的两个边界检查 我知道第二个while循环是多余的,因为[lo]充当哨兵,但简单地删除它似乎不起作用 public class Quick { // This class should not be instantiated. private Quick() { } /** * Rearranges the array in ascending order, using the natural order.
public class Quick {
// This class should not be instantiated.
private Quick() { }
/**
* Rearranges the array in ascending order, using the natural order.
* @param a the array to be sorted
*/
public static void sort(Comparable[] a) {
StdRandom.shuffle(a);
sort(a, 0, a.length - 1);
}
// quicksort the subarray from a[lo] to a[hi]
private static void sort(Comparable[] a, int lo, int hi) {
if (hi <= lo) return;
int j = partition(a, lo, hi);
sort(a, lo, j-1);
sort(a, j+1, hi);
assert isSorted(a, lo, hi);
}
// partition the subarray a[lo..hi] so that a[lo..j-1] <= a[j] <= a[j+1..hi]
// and return the index j.
private static int partition(Comparable[] a, int lo, int hi) {
int i = lo;
int j = hi + 1;
Comparable v = a[lo];
while (true) {
// find item on lo to swap
while (less(a[++i], v))
if (i == hi) break;
// find item on hi to swap
while (less(v, a[--j]))
if (j == lo) break;
// check if pointers cross
if (i >= j) break;
exch(a, i, j);
}
// put partitioning item v at a[j]
exch(a, lo, j);
// now, a[lo .. j-1] <= a[j] <= a[j+1 .. hi]
return j;
}
/**
* Rearranges the array so that a[k] contains the kth smallest key;
* a[0] through a[k-1] are less than (or equal to) a[k]; and
* a[k+1] through a[N-1] are greater than (or equal to) a[k].
* @param a the array
* @param k find the kth smallest
*/
public static Comparable select(Comparable[] a, int k) {
if (k < 0 || k >= a.length) {
throw new IndexOutOfBoundsException("Selected element out of bounds");
}
StdRandom.shuffle(a);
int lo = 0, hi = a.length - 1;
while (hi > lo) {
int i = partition(a, lo, hi);
if (i > k) hi = i - 1;
else if (i < k) lo = i + 1;
else return a[i];
}
return a[lo];
}
}
公共类快速{
//不应实例化此类。
私有快速(){}
/**
*使用自然顺序按升序重新排列数组。
*@param a要排序的数组
*/
公共静态无效排序(可比[]a){
施特兰多姆·沙夫勒(a);
排序(a,0,a.长度-1);
}
//将子阵列从[lo]快速排序到[hi]
私有静态无效排序(可比较的[]a,int-lo,int-hi){
如果(嗨我不确定我是否理解你的问题
if (i == hi) break;
这是:
if (j == lo) break;
可以删除,那么我回答否
这些检查非常重要,特别是当数组已经排序时。如果删除这些检查,在排序的数组中,less(a[++i],v)
永远不会false
,并且在尝试计算a[hi+1]
时会抛出ArrayIndexOutOfBoundsException
至于第二个while循环,你需要它和第一个while循环一样。第一个while循环查找索引最低的i
wherea[i]>a[lo]
,第二个while循环查找索引最高的j
wherea[j]我认为你的假设是错误的,需要两个循环。