学习编码,我将参加 2019 年初的训练营,并希望为此做好准备。我有一本 Java 书,其中包含以下代码作为快速排序算法的示例,我直接从书中复制了它,它为我提供了 IndexOutOfBounds 错误。我知道这与正在检查但可能不存在的索引位置有关,但是,我无法具体说明问题所在。有什么帮助吗?提前致谢。
// Try This 6-3: A simple version of the Quicksort.
class Quicksort {
// Set up a call to the actual Quicksort method.
static void qsort(char items[]) {
qs(items, 0, items.length-1);
}
// A recursive version of Quicksort for characters.
private static void qs(char items[], int left, int right)
{
int i, j;
char x, y;
i = left; j = right;
x = items[(left+right)/2];
do {
while((items[i] < x) && (i < right))
i++;
while((x < items[j]) && (j > left))
j--;
if(i <= j) {
y = items[i];
items[i] = items[j];
items[j] = y;
i++;
j--;
}
} while(i <= j);
if(left < j);
qs(items, left, j);
if(i < right)
qs(items, i, right);
}
}
class QSDemo {
public static void main(String args[]) {
char a[] = {'d', 'x', 'a', 'r', 'p', 'j', 'i'};
int i;
System.out.println("Original array: ");
for(i = 0; i < a.length; i++)
System.out.print(a[i]);
System.out.println();
// now, sort the array
Quicksort.qsort(a);
System.out.print("Sorted array: ");
for(i = 0; i < a.length; i++)
System.out.print(a[i]);
}
}*emphasized text*
最佳答案
问题是你放了一个;
在if
之后声明,这就是您收到错误的原因。因为;
, qs()
无论if
如何,都会被调用条件。
if(left < j); qs(items, left, j); //<------problem
____________^
if(left < j); qs(items, left, j);
应该是 if(left < j) qs(items, left, j);
关于java - 快速排序 - 线程 "main"java.lang.ArrayIndexOutOfBoundsException : -1 中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53147698/