QuickSort随机数据透视

时间:2016-03-01 21:39:20

标签: java algorithm sorting quicksort

我正在尝试实现QuickSort的一个版本,其中选择了一个随机数,通过生成边界从低到高的随机数并取其中间值。

然而,当我这样做时,代码运行得非常慢。如果我尝试使用29个元素对数组进行排序,则它可以使用2秒,但是一旦我将大小增加到30+(包括(30)),算法运行速度极慢。使用30个元素对数组进行排序大约需要10秒+,如果我更高一点就可以获得这个想法。

如果我有一个固定的支点,这不是问题。我可以排序一个大小为100 000的数组而没有任何问题。

我不知道什么是错的,需要一些帮助来弄清楚当我生成一个随机支点时它运行得如此之慢的原因。

问候!

protected int Partition(int[] v, int low, int high, boolean FixedPivot)
{
    int pivot = 0;
    if(!FixedPivot)
        pivot = RandomPivot(v, low, high); //If I pick a random pivot point then it runs extremly slow for some reason.
    else
        pivot = FixedPivot(v, low, high); //This one works fine, I can sort quickly without any problem.

    int i = low - 1;
    int j = high + 1;
    while(true)
    {
        do j--; while(v[j] > pivot);
        do i++; while(v[i] < pivot);
        if(i < j)
            Swap(v, i, j);
        else
            return j;
    }
}
protected int FixedPivot(int[] v, int low, int high)
{
    int average = (low + high) / 2;
    return Math.max(Math.min(v[low], v[average]), Math.min(Math.max(v[low], v[average]), v[high]));
}
protected int RandomPivot(int[] v, int low, int high)
{
    int X = 0;
    int Y = 0;
    int Z = 0;
    Random random = new Random();
    int range = (high - low) + low;
    if(range > 0)
    {
        X = random.nextInt(range);
        Y = random.nextInt(range);
        Z = random.nextInt(range);
    }
    return Math.max(Math.min(v[X], v[Y]), Math.min(Math.max(v[X], v[Y]), v[Z]));
}

1 个答案:

答案 0 :(得分:2)

我认为问题是random.nextInt(range);介于0high之间,您希望它介于lowhigh之间。以下是解决方法:

int range = (high - low);
if(range > 0)
{
    X = random.nextInt(range) + low;
    Y = random.nextInt(range) + low;
    Z = random.nextInt(range) + low;
}
相关问题