I tried implementing QuickSort off the top of my head for practice but I am getting out of bounds exception: 6 during compilation. I thought I properly used the setter method to assign array but it seems something is still wrong...
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:
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! ;-)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.