Answer the question
In order to leave comments, you need to log in
Why doesn't quicksort work in Java?
Hello Lord! Difficulties arose when implementing the quicksort algorithm in such a way that the reference element in the Partition procedure is always the last element of the current array. Algorithm and my code is below
public static int[] quickSort(int arr[], int p, int r){
if(p < 2){
int q = partition(arr, p, r);
quickSort(arr, p, q-1);
quickSort(arr, q+1, r);
}
return arr;
}
private static int partition(int[] arr, int p, int r) {
int x = arr[r];
int i = p-1;
for (int j = p; j < r; j++){
if(arr[j] < x){
count++;
i++;
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
System.out.println(count);
System.out.println(Arrays.toString(arr));
}
int t = arr[r];
arr[r] = arr[i+1];
arr[i+1] = t;
return i+1;
}
int x = arr[r];
Answer the question
In order to leave comments, you need to log in
Lord! Allowed! Swap did it wrong. Working code below
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
int t = arr[i+1];
arr[i+1] = arr[r];
arr[r] = t;
public static int[] quickSort(int arr[], int p, int r){
if(p < r){
int q = partition(arr, p, r);
quickSort(arr, p, q-1);
quickSort(arr, q+1, r);
}
return arr;
}
private static int partition(int[] arr, int p, int r) {
int x = arr[r];
int i = p-1;
for (int j = p; j < r; ++j){
count++;
if(arr[j] < x){
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
System.out.println(Arrays.toString(arr));
}
int t = arr[i+1];
arr[i+1] = arr[r];
arr[r] = t;
return i+1;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question