我试图更好地理解“快速排序算法”,我了解代码下面会发生什么。
但是当我写它的时候,我得到了著名的java.lang.ArrayIndexOutOfBoundsException
。
我暂时看不到数组的索引在哪里并且一直在混乱,但无济于事。
这是我的代码
打包QuickSort;
public class quickSort {
public static void main(String[] args) {
int[] array = {9,4,6,3,7,1,2,11,5};
printArray(array);
//10 sort(array, 0, array.length - 1);
}
//Partition Method Algorithm
static int partition(int arr[], int start, int end) {
//Start pivot at the last Index
int pivot = arr[end];
//The partition index checks if the number which was last switched
//19 int partitionIndex = start;
for(int i = start; start < end; i++) {
if(arr[i] <= pivot) {
int temp = arr[i];
arr[i] = arr[partitionIndex];
arr[partitionIndex] = temp;
partitionIndex++;
}
}
int temp = arr[partitionIndex];
arr[partitionIndex] = end;
arr[end] = temp;
return partitionIndex;
}
//Recursive function:
//piviotIndex is returned and keeps track of where the partition ends for the LHS
//PivotIndex keeps track of where the RHS partition starts
static void sort(int arr [], int start, int end) {
if(start<end) {
//52 int pivotIndex = partition(arr, 0, end);
partition(arr, start, pivotIndex-1);
partition(arr, pivotIndex+1, end);
}
}
static void printArray(int arr[]) {
for(int i : arr)
System.out.print(i + ", ");
}
}
我收到的错误消息是
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at QuickSort.quickSort.partition(quickSort.java:19)
at QuickSort.quickSort.sort(quickSort.java:52)
at QuickSort.quickSort.main(quickSort.java:10)
答案 0 :(得分:1)
更改
for(int i = start; start < end; i++) {
到
for(int i = start; i < end; i++) {
答案 1 :(得分:0)
如果您真的想检查start 但是我仍然可以看到您的代码没有打印排序的数组for(int i = start; i < end && start < end; i++)
or if not then
for(int i = start; i < end ; i++)