Ich habe versucht, QuickSort von der Spitze meines Kopfes zum Üben umzusetzen, aber ich bekomme außerhalb der Grenzen Ausnahme: 6 während der Kompilierung. Ich dachte, ich richtig die Setter-Methode verwendet Array zuweisen, aber es scheint immer noch etwas nicht stimmt ...Was ist los mit meiner QuickSort-Implementierung
Unten ist mein 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]+" ");
}
}
}
1> Ich denke, dass Sie meinen, dass Sie während der Laufzeit eine Out-of-Bound-Ausnahme erhalten. 2> Ist dem Fehler eine Zeilennummer zugeordnet? Wo ist es in Bezug auf Ihr Code-Snippet? – synchronizer
'highIndex-lowIndex/2' ist nicht das, was Sie denken, dass es ist. – user2357112