Ich versuche, einen QuickSort-Algorithmus als Hausaufgabe an der Universität zu implementieren, aber ich verstehe einfach nicht, wo ein Fehler in meinem Code ist. Ich nehme an, es ist ein logischer Fehler, ich glaube, ich tausche meinen Drehpunkt falsch. Ich könnte wirklich Hilfe gebrauchen, danke im Voraus. Es ist der Code:QuickSort Java-Implementierungsproblem
public class QuickSort {
private int [] array;
public QuickSort(int [] array){
this.array = array;
}
public void sort(){
partition(0, array.length - 1);
}
public void partition(int start, int end){
if (end - start < 2){
return;
}
int pivot_index = end;
int i = start;
int j = end - 1;
while (i < j){
//both elements are not in the right place
if(array[i] > array[pivot_index] && array[j] <= array[pivot_index]){
swap(array, i, j);
i++;
j--;
}
//the element on the left is not in place
else if (array[i] > array[pivot_index] && array[j] > array[pivot_index]){
j--;
}
//the element on the right is not in place
else if (array[i] < array[pivot_index] && array[j] < array[pivot_index]){
i++;
}
//both elements are in place
else {
i++;
j--;
}
}
if (array[i] > array[pivot_index]){
swap(array, pivot_index, i);
pivot_index = i;
}
partition(start, pivot_index - 1);
partition(pivot_index + 1, end);
}
private static void swap(int [] tab, int index1, int index2){
int temp = tab[index1];
tab[index1] = tab[index2];
tab[index2] = temp;
}
}
löst die folgende Antwort Ihr Problem? –
Beschreiben Sie das Verhalten, das Sie beobachten, und wie dies falsch ist. Was hast du getan, um herauszufinden, was schief läuft? Worauf haben Sie Ihre Implementierung basiert? – greybeard
@greybeard Ich habe den Algorithmus an vielen Beispielen mit der Debug-Funktion beobachtet. In einigen Beispielen funktioniert es, in anderen nicht. Das Sortierproblem tritt normalerweise auf, wenn sich wiederholte Elemente im Array befinden. Ich verstehe, wie es genau funktioniert, aber ich verstehe nicht, was ich hinzufügen sollte, damit es funktioniert. Zum Beispiel gibt es die Eingabe-Array: ** 19 3 10 9 2 1 4 19 ** und die Ausgabe nach der Sortierung: ** 1 2 3 4 9 19 10 19 ** –