我一直在尝试学习Java中的算法,并一直在尝试实现Hoares分区,并且一直在研究多个示例,但是当我尝试在intellij中实现时,出现此错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 6
at QuickSort.partitionSort(QuickSort.java:18)
at QuickSort.quickSort(QuickSort.java:35)
at QuickSort.main(QuickSort.java:52)
我不确定如何解决这个问题,因为我刚刚开始学习
import java.io.*;
public class QuickSort {
static int partitionSort(int[] arr, int h, int l) {
int i = l - 1;
int j = h + 1;
int pivot = arr[l];
while(true) {
do {
i++;
} while(arr[i] < pivot);
do {
j--;
} while(arr[j] > pivot);
if (i >= j)
return j;
int tempArr = arr[i];
arr[i] = arr[j];
arr[j] = tempArr;
}
}
static void quickSort(int[] arr, int l, int h) {
if (l > h)
return;
int q = partitionSort(arr, l, h);
quickSort(arr, l, q);
quickSort(arr, q + 1, h);
}
static void pArray(int[] arr, int n) {
for (int i = 0; i < n; i++) {
System.out.print(" " + arr[i]);
System.out.println();
}
}
public static void main(String args[]) {
int arr[] = {5, 8, 10, 3, 4, 1};
int n = arr.length;
quickSort(arr, 0, n - 1);
System.out.println("Before sorting: " + arr);
System.out.println("Sorted array: ");
pArray(arr, n);
}
}
答案 0 :(得分:1)
partitionSort的索引参数被反转。另外我的Java版本不允许System.out.println(“ Sorted array:” + arr);这应该在进行排序之前完成。您可能会考虑在partitionSort中使用中间值作为数据透视。
import java.io.*; // is this needed?
public class QuickSort {
static int partitionSort(int[] arr, int l, int h) { // fix, swap l and h
int i = l - 1;
int j = h + 1;
int pivot = arr[l]; // might want to use int pivot = arr[l + (h-l)/2];
while(true) {
do { // could be while(arr[++i] < pivot);
i++;
} while(arr[i] < pivot);
do { // could be while(arr[--j] > pivot);
j--;
} while(arr[j] > pivot);
if (i >= j)
return j;
int tempArr = arr[i];tempArr
arr[i] = arr[j];
arr[j] = tempArr;
}
}
static void quickSort(int[] arr, int l, int h) {
if (l >= h) // fix, if l >= h, nothing to do
return;
int q = partitionSort(arr, l, h);
quickSort(arr, l, q);
quickSort(arr, q + 1, h);
}
static void pArray(int[] arr, int n) {
for (int i = 0; i < n; i++) {
System.out.print(" " + arr[i]);
System.out.println();
}
}
public static void main(String args[]) {
int arr[] = {5, 8, 10, 3, 4, 1};
int n = arr.length;
System.out.println("Before sorting: "); // changed
pArray(arr, n); // changed
quickSort(arr, 0, n - 1);
System.out.println("Sorted array: ");
pArray(arr, n);
}
}