randomized quick sort in Java need a suble fix?

若如初见. 提交于 2019-12-24 16:16:41

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/20694571/randomized-quick-sort-in-java-need-a-suble-fix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!