2017-02-11 2 views
0

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

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

+4

'highIndex-lowIndex/2' ist nicht das, was Sie denken, dass es ist. – user2357112

Antwort

0

Alles, was Sie fehlt ist eine Reihe von Klammern für die Durchsetzung Reihenfolge der Operationen. Ihre Fehlerausgabe war:

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)  

Und alles, was Sie brauchen, ist zu beheben 12 zu korrigieren Zeile wie folgt:

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

Jetzt Ihren Lauf Ausgabe sollte:

2 45 96 96 96 

So, jetzt Wenn Ihre Laufzeitausnahme behoben ist, können Sie sich auf Ihre Sortierlogik konzentrieren! ;-)

+0

Alternativ: 'int pivot = array [(lowIndex + highIndex)/2];' – synchronizer

+0

Java 8 Lösung: 'Stream.of (2, 45, 96, 1, 16) .sorted(). ForEach (x -> System .out.print (x + "")); ' –