透视为三个随机数的中位数

时间:2014-12-05 17:26:00

标签: java arrays sorting pivot quicksort

我正在开发一个程序,它使用快速排序对数组进行排序以显示运行时间。该程序选择三个随机数的中位数作为枢轴。但是,我不确定我是否做错了,因为每次运行此程序时都会出现以下错误:

"java.lang.StackOverflowError", 
at java.util.Random.nextInt(Unknown Source)
at SortingItems.quickSort(SortingItems.java:31)
at SortingItems.quickSort(SortingItems.java:69)   " I get this  specific message multiple times"

这是代码:

import java.util.Random;

public class SortingItems {
    static int x = 1000;
    static int array []  = new int[x];

    public static void main(String[] args) {

       long time;

       input(x, array);
       time = System.nanoTime();
       sort(array);
       System.out.println("Running time in ascending order " + (System.nanoTime() - time));

   }

   public static void sort(int[] array) {
       quickSort(array, 0, array.length - 1);
   }

   public static void quickSort(int[] array, int low, int high) {
       if (array == null || array.length == 0)
           return;

       if (low >= high)
           return;

       // Generating random numbers from 0 to the last element of the array
       Random f = new Random();
       int first = f.nextInt(array.length - 1);

       Random s = new Random();
       int second = s.nextInt(array.length - 1);

       Random t = new Random();
       int third = t.nextInt(array.length - 1);



       // Selecting the pivot
       int pivot = Math.max(Math.min(array[first], array[second]),
                   Math.min(Math.max(array[first],array[second]), array[third]));

       int i = low;
       int j = high;

       while (i <= j) {
            while (array[i] < pivot) {
                  i++;
            }

            while (array[j] > pivot) {
                  j--;
            }

            if (i <= j) {
                 int temp = array[i];
                 array[i] = array[j];
                 array[j] = temp;
                 i++;
                 j--;

            }
      }

      if (low < j)
          quickSort(array, low, j);

      if (high > i)
          quickSort(array, i, high);

  }

  // Input in ascending order
  public static int[] input(int x, int[] array) {
       for (int k = 0; k < x; k++) {
            array[k] = k;
       }
       return array;

  }
}

1 个答案:

答案 0 :(得分:0)

问题似乎在于如何选择中位数。枢轴应从当前highlow位置之间选择,而不是整个阵列。

请注意,您的测试输入按升序排列。现在,当您从整个1000大小的数组中选择三个随机值进行旋转时,当涉及较小的递归情况时,数组倾向于以非常高的概率倾斜。这意味着将使用相同的输入参数调用另一级递归。从长远来看,这可能会导致堆栈溢出的可能性很高。

以下更改应解决您的问题:

// Generating random numbers from low to high
Random f = new Random();
int first = f.nextInt(high-low) + low;

Random s = new Random();
int second = s.nextInt(high-low) + low;

Random t = new Random();
int third = t.nextInt(high-low) + low;