随机快速排序在Java中需要suble解决? [英] randomized quick sort in Java need a suble fix?

查看:206
本文介绍了随机快速排序在Java中需要suble解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了快速排序算法,使用列表作为支点的第一个元素,它工作得很好。我现在重构来选择一个随机指数作为主元,交换的第一个元素,并做快速排序子程序。不知何故,这是行不通的,我没有得到的排序的数组。 这里是我的code,这是不言自明,但我很高兴,如果任何疑问需要解释。

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));
      }
}

我已经注释掉随机支点计算在code与***** 。我没有看到任何问题,但具有随机支点计算破坏了code

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

推荐答案

你的code,其余是确定的,但

the rest of your code is OK,but

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

有一些问题。 考虑结束==开始,然后你长了pivID == 1 +启动。

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

这篇关于随机快速排序在Java中需要suble解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆