The expected run time of the Randomized_select function is θ (n), where the input data is assumed to be mutually dissimilar. It returns the small element in the array a[p, R]. The worst-case run of this function is θ (n2), even if the smallest element is found, so that it may be extremely unlucky to divide each partition by the largest of the remaining elements, while the partitioning operation requires θ (n) time. We will also see that the algorithm has a linear expected run time, and because it is randomized, there is no specific input data that will cause its worst-case occurrence.
Input: Array A, integer I (i is not greater than the number of arrays).
Output: An element of small I in array A.
Expected run time: Θ (n). Worst run Time: Θ (n2).
1#include <stdio.h>2#include <stdlib.h>3#include <time.h>4 5 Static intRandomized_select (int*,int,int,int);6 Static intRandomized_partition (int*,int,int);7 Static intPartitionint*,int,int);8 Static intRANDOMD (int,int);9 Static voidSwapint*,int*);Ten One A intMainintargcChar*argv[]) - { - the intmid; - intarray[9] = {1,2,4,7,3,5,6,8, A};
/* Returns the 5th small element. */ -MID = Randomized_select (array,0,8,5); -printf"%d\n", mid); + return 0; - } + A at Static intRandomized_select (int*a,intPintRinti) - { - intQ, K; - - if(p = =R) - returnA[p]; in -Q =randomized_partition (A, p, R); toK = q-p +1; + - if(i = =k) the returnA[q]; * Else if(I <k) $ returnRandomized_select (A, p, Q-1, i);Panax Notoginseng Else - returnRandomized_select (A, q +1, R, I-k); the } + A Static intRandomized_partition (int*a,intPintR) the { + intI, temp; -i =RANDOMD (P, r); $Swap (A + R, a +i); $ /* - temp = a[r]; - A[r] = a[i]; the A[i] = temp; - */ Wuyi returnpartition (A, p, R); the } -/* divided, as with the quick sort. */ Wu Static intPartitionint*a,intPintR) - { About intA, I, J, temp; $A =A[r]; -i = P-1; - - for(j = P; J < R; + +)j) A { + if(A[j] <=a) the { -++i; $Swap (A + j, a +i); the /* the temp = a[j]; the A[j] = a[i]; the A[i] = temp; - */ in } the the } About theSwap (A + R, a + i +1); the /* the temp = a[r]; + A[r] = a[i + 1]; - a[i + 1] = temp; the */Bayi returni +1; the } the -/* Returns a random number within a specified range [a, b]. */ - Static intRANDOMD (intAintb) the { the intQ; the theSrand ((unsignedint) Time (NULL)); -Q = rand ()% (B-a +1) +A; the the returnQ; the }94 the/* Swap values. */ the Static voidSwapint*NUM1,int*num2) the {98 inttemp; Abouttemp = *NUM1; -*NUM1 = *num2;101*num2 =temp;102}
Selection algorithm for linear time of expectation