我的 QuickSort 实现有什么问题

What is wrong with my QuickSort Implementation

我试着在脑海中实现 QuickSort 进行练习,但我在编译期间遇到了越界异常:6。我以为我正确地使用了 setter 方法来分配数组,但似乎仍然有问题...

下面是我的代码:

public class MyClass {
private int array[];

public void setArray(int[] arr){
    this.array=arr;
    quickSort(0,array.length-1);

    }

    private int length;
    private void quickSort(int lowIndex, int highIndex){
        int pivot = array[lowIndex+(highIndex-lowIndex/2)]; // our pivot
        int i = lowIndex;
        int j = highIndex;
        while(i<=j){
            while(array[i]<pivot){
                i++;
            }
            while(array[j]>pivot){
                j--;
            }
            if(i<=j){
                int temp = array[i];
                array[j] = array[i];
                array[i] = temp;
                i++;
                j--;
            }

        }
        if(lowIndex<j){
            quickSort(lowIndex, j);
        }
        if(highIndex>i){
            quickSort(i, highIndex);
        }


    }


    public static void main(String[] args) {
        int[] array2 = {2,45,96,1,16};
     MyClass b = new MyClass ();
     b.setArray(array2);
     for(int x=0;x<array2.length;x++){
         System.out.print(array2[x]+" ");
     }
    }
}

您所缺少的只是一组用于执行操作顺序的括号。你的错误输出是这样的:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
    at MyClass.quickSort(MyClass.java:12)
    at MyClass.quickSort(MyClass.java:35)
    at MyClass.setArray(MyClass.java:6)
    at MyClass.main(MyClass.java:45)    

您只需按如下方式更正第 12 行:

int pivot = array[lowIndex+((highIndex-lowIndex)/2)]; // our pivot
                            ^                  ^

现在您的 运行 输出应该是:

2 45 96 96 96 

现在您的 运行 时间异常已修复,您可以专注于排序逻辑! ;-)