[Java]
/**
* Linear selection of recursive grouping Algorithms
*/
Recursive grouping of package;
/*
* Linear Selection Algorithm
* Given n elements in a linear sequence and an integer k, 1 ≤ k ≤ n, the minimum k element of the n elements must be found.
* In the worst case, the algorithm randomizedSelect requires O (n2) computing time, www.2cto.com
* It can be proved that the algorithm randomizedSelect can find the k-small element of n input elements in the O (n) Average time.
*/
Import java. util. Random;
Public class randomizedSelectTest {
Private static int randomizedPartition (int [] a, int p, int r ){
Int I = random (p, r );
Swap (a, I, p); // switch the hub element to the left end of the Interval
Return partition (a, p, r );
}
/**
* Linear selection of k-small elements in the specified array
* @ Param a specify an array
* @ Param p range left end
* @ Param r range right end
* @ Param k the size and position of the array
* @ Return returns the minimum k element in the specified array.
*/
@ SuppressWarnings ("unused ")
Private static int randomizedSelect (int [] a, int p, int r, int k ){
If (p = r) return a [p];
Int I = randomizedPartition (a, p, r );
Int j = I-p + 1; // number of elements on the left end
// The smallest k element is on the left side.
If (k <= j) return randomizedSelect (a, p, I, k );
Else // the k-th element is on the right side, and the left side already has j elements smaller than it
// You only need to find the smallest k-j element in the right end.
Return randomizedSelect (a, I + 1, r, k-j );
}
Private static int random (int I, int j ){
Random r = new Random ();
Return r. nextInt (j-I) + I;
}
Private static int partition (int [] a, int p, int r ){
Int I = p, j = r + 1;
Int x = a [p];
While (true ){
While (a [++ I] <x & I <r );
While (a [-- j]> x );
If (I> = j) break;
Swap (a, I, j );
}
A [p] = a [j];
A [j] = x;
Return j;
}
Private static void swap (int [] a, int I, int j ){
Int temp = a [I];
A [I] = a [j];
A [j] = temp;
}
Public static void main (String [] args ){
}
}