0

解決済み:再帰呼び出しごとに新しい Random オブジェクトをインスタンス化していました。Quicksort から静的変数として配置したところ、完全に正常に動作するようになりました。

学校の宿題のために Java で Quicksort をプログラミングしていますが、行き詰まってしまいました。クラスのnextInt()メソッドを使用してランダムにピボットを選択しています。これは、すべての再帰ステップでRandom呼び出していることを意味します。nextInt()私のクイックソートは、20000 個の要素を持つ配列で完全に機能します。しかし、40000要素の配列をソートしようとすると、これStackOverflowErrorが表示されます

   java.lang.StackOverflowError: null (in java.util.Random)

Googleでこのエラーを検索しましたが、何も役に立ちません。私の推測では、私はランダムな int を使い果たしたのですが、私は Java に慣れていないので、自分で推測することさえしません。

これが私のコードです(スペイン語は私の第一言語です。不自由な英語とスペイン語のコードで申し訳ありません)

public static void quicksort(String[] A, int min, int max){// llamar ord(A, 0, n-1);
    if(min >= max){
        return;
    }
    Random rand = new Random(); 
    int pivote = particionar(A, min, max, rand);
    quicksort(A, min, pivote-1);
    quicksort(A, pivote + 1, max);
    }

public static int particionar(String[] A, int min, int max, Random rand){    
    int menores = min + 1;
    int mayores = max;

    int pivote = rand.nextInt(max-min+1) + min;
    String pivotstr = A[pivote];
    //dejar pivote al principio
    String aux = A[min];
    A[min] = A[pivote];
    A[pivote] = aux;

    while(menores <= mayores){
        if(A[menores].compareTo(pivotstr) <= 0){
            menores++;
        }
        else{//intercambiar
            String aux2 = A[menores];
            A[menores] = A[mayores];
            A[mayores] = aux2;
            mayores--;
        }
    }
    //mover pivote donde corresponde
    String aux3 = A[min];
    A[min] = A[mayores];
    A[mayores] = aux3;

    return mayores;

}
4

2 に答える 2

0

StackOverflowError は、再帰が深すぎる場合に得られるものです。

解決策: 反復バージョンに変換します。 再帰から反復への道

于 2013-06-14T06:47:12.203 に答える