Quicksort algorithm program in Java

I'm trying to implement the Quicksort algorithm program in Java, but I got the wrong answer

public class QuickSort {

    public static void main(String[] args){
        int arr[]={12,34,22,64,33,23,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,j);

        return quickSort(arr,j);

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

}

The output given by the above program is: 12 23 22 33 34 64 34 64

Who can tell me how to get the result I want?

Solution

The problem is that it's not really how quicksort works Quicksort is a recursive algorithm that can only be called once from the outside Our idea is that in each iteration, you divide the array into two halves - the left half contains all elements less than the pivot and the right half contains all elements greater than / equal to the pivot Then you quickly divide the two halves and finally put the pivot in the middle

If the length of one side of your quick allocation is less than 3 elements, you can exchange only these two elements or keep them and complete this part of the array

But your code doesn't look like this - you call quicksort six times from your client, and you only exchange once at most in the Quicksort function So this is not a situation where one can view your code and debug it by telling you mobile switching or other things You need to review your logic

Check the Wikipedia chart for a visual example of what should happen in an iteration:

http://en.wikipedia.org/wiki/File:Partition_example.svg

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>