简体   繁体   中英

randomized quick sort in Java need a suble fix?

I have implemented the quicksort algorithm that uses the first element of the list as pivot and it worked fine. now I refactored to pick a random index as pivot element, swap with the first element and do the quicksort subroutine. somehow, it does not work, I do not get the sorted array. here is my code, which is self-explanatory, but I am happy to explain if any clarification needed.

public class Qsort {
       public static void quickSort2(int[] arr, int i, int j){
        if (i<j){
            int part =randPartition(arr, i, j);
            quickSort2(arr, i, part-1);
            quickSort2(arr, part+1, j); 
        }
    }
    public static int randPartition(int[] arr, int start, int end){
        //int pivId = (int)(Math.random()*(end-start)+1)+start; -- *****
        int pivId = start;
        //System.out.println("pivId is "+ pivId + "; start is " + start + "; end is " + end);
        System.out.println("arr is "+ Arrays.toString(arr));
        int pivot = arr[pivId];
        swap(arr, start, pivId);
        int i = start;

        for (int j = start+1;j<=end;j++){
            if (arr[j]<pivot){
                    i++;
                    swap(arr,i,j);
            }
        }
        swap(arr, start,i);
        return i;
    }

   private static void swap(int[] arr, int index1, int index2) {
        int temp = arr[index1];
        arr[index1]=arr[index2];
        arr[index2]=temp;
    }

   public static void main(String[] args) {
        int[] data2 = new int[]{10,11,9,7,5};
        System.out.println("Unsorted array data " + Arrays.toString(data2));
        quickSort2(data2, 0, data.length-1);
        System.out.println("Sorted array data " + Arrays.toString(data2));
      }
}

I have commented out the random pivot calculation in the code with ***** . I dont see any problem with it, but having the random pivot calculation destroys the code

the rest of your code is OK,but

int pivId = (int)(Math.random()*(end-start)+1)+start; -- *****

has some problems. Consider end == start, then u got pivID == 1+start.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM