Dusk - 1 month ago 26
Java Question

# Quicksort algorithm program in Java

I'm trying to implement QuickSort algorithm program in Java, but I'm getting incorrect answer.

``````public class QuickSort {

public static void main(String[] args){
int arr[]={12,34,22,64,34,33,23,64,33};
int i=0;
int j=arr.length;
while(i<j){
i=quickSort(arr,i,i+1,j-1);

}
for(i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
}

public static int quickSort(int arr[],int pivot,int i,int j){

if(i>j) {
swap(arr,pivot,j);
return i;
}

while(i<arr.length&&arr[i]<=arr[pivot]) {
i++;
}

while(j>=1&&arr[j]>=arr[pivot]) {
j--;
}
if(i<j)
swap(arr,i,j);

return quickSort(arr,pivot,i,j);

}
public static void swap(int[] arr,int i,int j) {
int temp;
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}

}
``````

The above program giving me the output as: 12 23 22 33 34 33 64 34 64

Could anyone please tell me how can I get my desire result?

But it doesn't look like your code is doing that at all - you are calling Quicksort 6 times from your client, and within the `quicksort` function you are making at most one swap. So this is not a case where someone is going to be able to look at your code and debug it by telling you to move a swap or something. You need to revisit your logic.