简体   繁体   English

我的QuickSort实施有什么问题

[英]What is wrong with my QuickSort Implementation

I tried implementing QuickSort off the top of my head for practice but I am getting out of bounds exception: 6 during compilation. 我尝试从头顶实现QuickSort进行练习,但是我越界越好:编译期间出现6。 I thought I properly used the setter method to assign array but it seems something is still wrong... 我以为我正确地使用了setter方法来分配数组,但似乎还是有问题的...

Below is my code: 下面是我的代码:

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]+" ");
     }
    }
}

All that you're missing is a set of parenthesis for enforcing order of operations. 您所缺少的只是一组用于强制执行操作顺序的括号。 Your error output was this: 您的错误输出是这样的:

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)    

And all you need to fix is to correct line 12 as follows: 您所需要做的就是纠正第12行,如下所示:

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

Now your run output should be: 现在,您的运行输出应为:

2 45 96 96 96 

So now that your runtime exception is fixed, you can focus on your sort logic! 因此,现在您的运行时异常已修复,您可以专注于排序逻辑! ;-) ;-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM