The linear time selection problem, in fact, is an extension of the random fast sorting algorithm, IE, can be achieved by small changes to the random fast sorting algorithm.
The algorithm still refers to the relevant content in the introduction of the algorithm, it is important to note that
The ID in the code refers to the position of the quantity you are looking for in the existing interval "low, high", and therefore involves a certain conversion. Ps:mid-low + 1 represents the length of the first interval we divide.
The source code is as follows:
//===================== "Random selection" ==================//@ author:zhyh2010//@ date:20150606//@ version:1.0//@ Description://===================== "Random selection" ==================#include <stdio.h>#include <stdlib.h>#define NUMintArr[num] = {0};voidInit () {time_t TM; Time (&TM); Srand ((unsigned int) tm);intMax_item = -; for(inti =0; I! = NUM; i++) Arr[i] = rand ()% Max_item;}voidSwapint* PA,int* Pb) {intAA = *PA;intbb = *PB; aa = aa ^ bb; bb = aa ^ bb; aa = aa ^ bb; *PA = AA; *PB = BB;}voidDisplayint* arr) { for(inti =0; I! = NUM; i++) printf ("%-10d", Arr[i]); printf"\ n");}intPartition (intLowintHigh) {intPrivot = Arr[high];inti = low-1; for(intj = Low; J! = high; J + +) {if(Arr[j] <= privot) swap (&arr[j], &arr[++i]); } Swap (&arr[i +1], &arr[high]);returni +1;}intRandompartition (intLowintHigh) {time_t TM; Time (&TM); Srand ((unsigned int) tm);int ID= rand ()% NUM; Swap (&arr[ID], &arr[num-1]);returnPartition (Low, High);}intRandomselect (intLowintHighint ID){if(Low >= High)returnArr[low];intMID = Randompartition (low, high);intK = Mid-Low +1;if(k = =ID)returnArr[mid];if(ID> k)returnRandomselect (Mid +1, High,ID-K);Else returnRandomselect (Low, mid-1,ID); }voidMain () {init (); Display (arr);intK =5;intres = Randomselect (0, NUM-1, k); printf"The%d th number of the arr is%d\n", K, res);}
C Implementation method of linear time selection for classical algorithm