简体   繁体   English

Java中的随机快速排序是否需要Suble修复?

[英]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. 我已经实现了quicksort算法,该算法将列表的第一个元素用作数据透视,并且效果很好。 now I refactored to pick a random index as pivot element, swap with the first element and do the quicksort subroutine. 现在,我refactored为选择一个随机索引作为枢轴元素,与第一个元素交换并执行quicksort子例程。 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 ***** . 我已经random pivot calculation in the code with *****注释掉了random pivot calculation in the code with *****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. 考虑end == start,然后得到pivID == 1 + start。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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