problem Description: given the n elements in a linear sequence set and an integer k,1≤k≤n, it is required to find the nth element in the N element.
Algorithm Description:
Algorithm implementation:
#include <stdio.h>#include<stdlib.h>intMain () {voidSordintA[],intHintt); intSelectorder (intXintA[],intHintt); intPartitionintA[],intHintTintk); intN; scanf ("%d",&N); int*A; A=(int*)malloc(sizeof(int)*N); for(intI=0; i<n;i++) A[i]=rand (); for(intI=0; i<n;i++) printf ("%d", A[i]);//dynamically create array A and randomly generate array a element, output /*int n=15; int a[15]={41,58,96,7,5,857,589,415,27,398,215,86,71,88,85}; for (int i=0;i<n;i++) printf ("%d", A[i]);*/ //array used to check the programprintf"\ n"); intK; scanf ("%d", &k);//Input k intAnswer//order-1 if(k>n) printf ("Scan Error");//k>n, input error Else{Answer=selectorder (K-1A0, N-1);//Call the Selectorder function,//get the small element K and assign it to answerprintf"%d\n", answer); } Sord (A,0, N-1); for(intI=0; i<n;i++) printf ("%d", A[i]);//Select sort and output for elements in array A, in order to check the program return 0; } voidSordint*a,intHintT//Select Sort in array a (from H to t) elements{ inttemp; inti,j; for(i=h;i<=t-1; i++) for(j=i+1; j<=t;j++) if(a[i]>A[j]) {Temp=a[i];a[i]=a[j];a[j]=temp;} }intPartitionint*a,intHintTintK//array A (from H to t) according to Element K//dividing the left half of the element below K and the right half of the greater than K{ intI=h; intj=T; inttemp; while(i<j) { while(a[i]<k) i++; while(a[j]>k) j--; Temp=a[i];a[i]=a[j];a[j]=temp; } for(intj=h;j<=t;j++)if(a[j]==k) Break; A[J]=a[i];a[i]=K; returni;} intSelectorder (intXint*a,intHintt) { if(t-h+1< the) { if(t>h) Sord (a,h,t); returnA[x]; }//if the number of elements in the current array range is less than//Select sort the array elements in this range and return a[x] Else { inti; inttemp; for(i=0; I<= (t-h-4)/5; i++) {Sord (a,h+i*5, h+i*5+4); Temp=a[h+i]; A[h+i]=a[h+i*5+2]; A[h+i*5+2]=temp; }//divide n elements into a N/5 group,//Select a sort for each group,//Adjust the median of each group to the front of the array intK=selectorder (H + (t-h-4)/5)/2, a,h,h+ (t-h-4)/5); //Find out the median of the median of each group in the front of the arrayI=partition (A,H,T,K); //according to K array A (from H to t) is divided,//the left element value is smaller than k, the right element is larger than K,//returns the position of I as K in the array if(i==x)return(A[i]);//find the X+1 small element in the array Else { intj=i+1; if(X<J)returnSelectorder (x,a,h,i-1);//find the X+1 small element from the left half of the K array element Else returnSelectorder (x,a,j,t);//find the X+1 small element from the right half of the K array element } }}
Divide and conquer and recursive-linear time selection