Der Code ist ein Quicksort-Algorithmus mit einem zufälligen Pivot. Das zufällige Array wird nicht vollständig sortiert. Ich kann nicht herausfinden warum. Der Fehler scheint mit den Grenzen der rekursiven Aufrufe und Swapping zu sein.Quicksort (Random Pivot) Code nicht richtig sortiert Java
public static <E extends Comparable<E>> void quickerSort(ArrayList<E> input, int lower, int higher){
int first = lower;
int last = higher;
if (lower >= higher)
return;
//generates the random pivot
int pivot = rand.nextInt(higher-lower+1) + lower;
//moves the pivot to the beginning of the list
E temp = input.get(first);
input.set(first, input.get(pivot));
input.set(pivot, temp);
pivot = first;
first++;
//if the values on the left side of the array are less than the
//value of the pivot, first is incremented (first part of loop) until
//a greater value is reached
//if the values on the right side of the array are greater than the
//value of the pivot, last is incremented until a lesser value is reached
while (first < last){
while (input.get(first).compareTo(input.get(pivot)) <= 0 && first < last){
first++;
}
while(input.get(last).compareTo(input.get(pivot)) > 0 && last >= first){
last--;
}
//switches the two values reached through the while loops
if (first < last){
temp = input.get(first);
input.set(first, input.get(last));
input.set(last, temp);
}
}
//moves the pivot to where first is
temp = input.get(first-1);
input.set(first-1, input.get(pivot));
input.set(pivot, temp);
//calls the method recursively
if (lower < first-1){
quickerSort(input,lower,first-1);
}
if (first < higher){
quickerSort(input,first,higher);
}
}
// implementierende Methode
public static void testQuickSort(){
//creates a random list of integers to be sorted and prints it
ArrayList<Integer> list = new ArrayList<Integer>();
Random rand = new Random();
for (int i = 0; i <= 19; i++){
list.add(rand.nextInt(100));
System.out.print(list.get(i)+" ");
}
//calls quicksort and then prints the sorted array
System.out.println();
Assignment2.quickSort(list);
for (int i = 0; i <= 19; i++){
System.out.print(list.get(i)+" ");
}
}
Haben Sie versucht, mit [Musik] (https://www.youtube.com/watch?v=3San3uKKHgg)? * Es ist Freitag * –
Ernsthafter, einige Papier und ein Debugger könnten hilfreich sein, um herauszufinden –