实现使用随机数据透视而不是在QuickSort,java中选择第一个元素作为数据透视表

时间:2014-02-26 08:26:55

标签: java quicksort

所以这是我项目的源代码。如果"cmp(i,j)"i < j函数会返回负值,i > j会返回正值,0会返回i = j

如您所见,我选择列表的当前第一个元素作为pivot,这是有效的。现在我想使用随机数据透视。如果我只是做一个“int pivot = first + random.nextInt(last-first+1);"我在运行时遇到了很多错误。

源代码:

    public void sort(){ 
        sortQuick(0, getElementCount()-1);
    }
    public void sortQuick (int first, int last){
    // pivot tilldelas ett värde mellan noll och antal element i vektorn.
    //final Random random = new Random();
    System.out.println(("Last: " + last + ", first : " + first));
    //int pivot = first + random.nextInt(last-first+1);
    int pivot = first;
    System.out.println(pivot);
    int up = first;                          // index of left-to-right scan
    int down = last;                            // index of right-to-left scan

    if (last - first >= 1){               // check that there are at least two elements to sort

        // set the pivot as the first element in the partition

        while (down > up)  {                 // while the scan indices from left and right have not met,

            while (cmp(up,pivot) <= 0 && up <= last && down > up)  // from the left, look for the first
                up++;                                    // element greater than the pivot
            while (cmp(down,pivot) > 0 && down >= first && down >= up) // from the right, look for the first
                down--;                                     // element not greater than the pivot
            if (down > up){                                   // if the left seekindex is still smaller than
                swap(up, down);
            }
            // the right index, swap the corresponding elements
        }
        swap(first, down);          // after the indices have crossed, swap the last element in
                                    // the left partition with the pivot 
        sortQuick(first, down - 1); // quicksort the left partition
        sortQuick(down + 1, last);   // quicksort the right partition
    }
    else    // if there is only one element in the partition, do not do any sorting
    {
        return;                   // the array is sorted, so exit
    }
}

2 个答案:

答案 0 :(得分:0)

问题是当你做

int pivot = first + random.nextInt(last-first+1)

您之前没有检查过last > first。所以,您可能会遇到last < first,并尝试使用负(或零)参数调用random.nextInt(),这是没有意义的,因此您将获得IllegalArgumentException }。

您需要做的是在if()

中移动枢轴计算
if (last - first >= 1){               // check that there are at least two elements to sort
    int pivot = first + random.nextInt(last-first+1);

答案 1 :(得分:-1)

int smth = (int)(Math.random()-1);