私はクイックソルトを少しの練習として実装しています。現在のところ、これは単純な整数配列の単なる実装です。これが正常に機能した後、私はそれを一般的にする予定です。クイックソートの実装:ランダムピボットを使用するとほとんどソートされます
以下に記載している内容には、それでも私が追跡できなかったわずかな不具合があります。私はもともとピボットとして左インデックスを使用するように書いたが、すべてうまくいきました。しかし、いったん私はそれを書き終え、ランダムなピボットを使用するように切り替えると、物事はもう正しくはありません。私のテスト配列はほぼソートされていますが、いくつかの要素はまだ2〜3つのインデックスから離れています。ここで
はこの介して実行時に不正な動作を実証し、私のテストケースのほんの一部です:
6, 5, 1, 3, 8, 4, 7, 9, 2
1, 2, 3, 4, 5
5, 4, 3, 2, 1
/**
* Sort an integer array using quicksort
*
* @param a Array to sort
*/
public static void quicksort(int[] a) {
partition(0, a.length - 1, a);
}
/**
* Partition a section of an integer array around a randomly selected pivot within that section
*
* @param left Lower-bound index of section (inclusive)
* @param right Upper-bound index of section (inclusive)
* @param a Array to perform partitioning within
*/
private static void partition(int left, int right, int[] a) {
// Exit if partition is only a single element
if (right - left < 1) { return; }
// Select a pivot at random
int pivot = ThreadLocalRandom.current().nextInt(left, right + 1);
// Move pivot to left-most position (get out of the way)
swap(left, pivot, a);
// Perform partitioning
int cur = left + 1;
for (int i = left + 1; i <= right; i++) {
if (a[i] < a[pivot]) {
swap(i, cur, a);
cur++;
}
}
// Put pivot back where it belongs
swap(left, cur - 1, a);
// Partition the two new partitions
partition(left, cur - 2, a);
partition(cur, right, a);
}
/**
* Swaps two elements in an array of integers
*
* @param i Index of first element to swap
* @param j Index of second element to swap
* @param a Integer array to perform swap on
*/
private static void swap(int i, int j, int[] a) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
それはThreadLocalRandom可能性があり、物事は罰金に見える:それは、このパーティションのロジックに、あなたは、アレイ内の間違ったインデックスを見ていることを意味し+左?私はhttp://www.tutorialsp.com/compile_java8_online.phpでコードを実行しました。 –
気にしないでください。分かった。 –
左端の要素でピボット要素を交換していますが、パーティショニング手順で要素を比較する場合は、ピボットのインデックスを更新していません。私はそれが原因であるかどうかは分かりませんが、確かにあなたが調べたいかもしれないものです。 – templatetypedef