我试图做一个快速排序,但它总是显示错误ArrayIndexOutOfBoundsException。
public class Quicksort
{
void sort(int[] arr)
{
_quicksort(arr, 0, arr.length - 1);
}
private void _quicksort(int[] arr, int left, int right)
{
int pivot = (left + right)/2;
int l = left;
int r = right;
while (l <= r)
{
while (arr[l] < pivot)
{
l++;
}
while (arr[r] > pivot)
{
r--;
}
if(l <= r)
{
int temp = l;
l = r;
r = temp;
l++;
r++;
}
}
if(left < r)
{
_quicksort(arr, left, r);
}
if(l < right)
{
_quicksort(arr, l, right);
}
}
}
有人知道为什么它不运行吗?它总是给出一个错误。
错误消息是
java.lang.ArrayIndexOutOfBoundsException: -1
at Quicksort._quicksort(Quicksort.java:18)
at Quicksort._quicksort(Quicksort.java:33)
at Quicksort.sort(Quicksort.java:5)
您的代码似乎有几个问题。我在下面列出了它们:
该变量pivot
存储枢轴元素的索引,而不存储实际值。因此,不能pivot
像在两个嵌套的while循环中那样进行比较。您需要arr[pivot]
代替pivot
那里。
试想一下,arr
貌似{1, 1, 1, 3, 2, 2, 2}
。在这里,pivot
将等于3
即arr[pivot]
等于3
。现在,两个嵌套的while循环都终止之后,l
将等于3
并r
保持等于6
。然后arr[l]
,您交换和arr[r]
并增加l
和r
。由于l
仍小于等于r
,因此外部while循环将第二次运行,并且ArrayIndexOutOfBoundsExecption
当控件到达第二个嵌套while循环时,您将获得一个。发生这种情况是因为您尝试访问arr[7]
(超出范围)。
这是我的代码:
class Quicksort
{
void sort(int[] arr)
{
myQuicksort(arr, 0, arr.length - 1);
}
private void myQuicksort(int[] arr, int l, int r) {
if (l >= r) {
return;
}
int pivotIndex = (l + r) / 2;
swap (arr, r, pivotIndex);
int pivotValue = arr[r];
int swapIndex = 0;
int currentIndex = 0;
while (currentIndex != r) {
if (arr[currentIndex] < pivotValue) {
swap(arr, currentIndex, swapIndex);
swapIndex++;
}
currentIndex++;
}
swap(arr, r, swapIndex);
myQuicksort(arr, l, swapIndex - 1);
myQuicksort(arr, swapIndex + 1, r);
}
private void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
public class Main{
public static void main(String[] args) {
Quicksort quicksort = new Quicksort();
int[] arr = {3, 7, 1, 0, 4};
quicksort.sort(arr);
for (int i : arr) {
System.out.println(i);
}
}
}
您应该阅读Quicksort。但是这里是要点:
选择一个随机的枢轴元素并将其与最后一个元素交换。这使实现更加简单。
循环遍历输入数组,并跟踪a swapIndex
,使得之前的所有内容都swapIndex
小于,pivotValue
而从到swapIndex
之前的所有内容currentIndex
均大于(或等于)pivotValue
。
循环用完后,将处的元素swapIndex
替换为pivot
。这会将插入pivot
正确的位置。
所述pivot
划分成阵列的子阵列2。调用myQuicksort
这两个子数组。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句