Randomized quicksort (Randomized quick sort)
- Running time is independent of input ordering.
- No assumption about the input distribution. (no assumptions are made on the input sequence distribution)
- No specific input elicit the worst-case behavior. (No specific input causes the worst operating efficiency)
- Worst-case determined only by a random-number generator. (worst case is determined by the random number generator)
- Pivot a random element. (Randomly select one of the main elements)
The pseudo-code in the fast-sequenced randomized sample in the introduction to the algorithm is as follows:
Partitioning of arrays:
1 randomized-PARTITION (A, P, r)2 i = RANDOM (p, r)3Exchange A[r] with a[ I]4return PARTITION (A, p, R)
where partition (A, p, R) reference Quick sort (Java implementation)
1 randomized-QUICKSORT (A, P, r)2 if p < r3 q = randomized-PARTITION (A, p, r)4 randomized-quicksort (A, p, q-1)5 Randomized-quicksort (A, q+1, R)
Random fast sorting, randomly selecting a principal and array division: Randomquicksort.java
1 Packagequicksort;2 3 ImportJava.util.Random;4 5 Public classRandomquicksort {6 7 Public voidSort (int[] A,intPintr) {8 if(P <r) {9 intQ =Partition (A, p, r);TenSort (A, p, q-1); OneSort (a,q+1, R); A } - } - the Private intPartition (int[] A,intPintr) { - /*random selection of the main element*/ -Random random =NewRandom (); - intRandom_index = Random.nextint (r-p+1) +p; +System.out.println ("random_index=" +random_index); - inttemp =A[random_index]; +A[random_index] =A[r]; AA[R] =temp; at - intx = A[r];//pivot = a[p] - inti = P-1; - for(intj = P; J < R; J + +) { - if(A[j] <= x) {//Comparison with pivot -i++; in intTMP =A[j]; -A[J] =A[i]; toA[i] =tmp; + } - } the * intTMP =A[r]; $A[r] = a[i+1];Panax NotoginsengA[I+1] =tmp; - the returnI+1; + A } the +}
Quick ordering of test randomization: Randomquicksorttest.java
1 Packagequicksort;2 3 Public classRandomquicksorttest {4 5 //Static int[] A ={2, 8, 7, 1, 3, 5, 6, 4};6 Static int[] A ={13, 19, 9, 5, 12, 8, 7, 4, 21, 2, 6, 11};7 Public Static voidMain (string[] args) {8Randomquicksort Randomquicksort =NewRandomquicksort ();9Randomquicksort.sort (A, 0, a.length-1);Ten One for(inti = 0; i < a.length; i++) { ASystem.out.print (a[i]+ ""); - } - } the}
Test results:
random_index=2random_index=2random_index=0random_index=0random_index =8 Random_index=10random_index=7random_index
Randomized quick sort (Java implementation)