Problem Description: Given the set S consisting of n different numbers and the positive integer k < n, we try to design an O(n) time algorithm to find the number of K that is closest to the median of S.
Algorithmic description:
- Finding the Median with the Algorithms Realized by Linear Time Selection
- S'= S excluding median
- Value in S"=|S'- Value of Median|
- Finding the k-th Minimum Number by the Algorithms Implemented by Linear Time Selection
- Value in S corresponding to the number of output S less than the smallest number in k
Algorithmic implementation:
selectorder Function, partition Function, sord The function is implemented with the algorithm of linear time selection program. int main() { void sord(int a[],int h,int t); int selectorder(int x,int a[],int h,int t); int partition(int a[],int h,int t,int k); int n; scanf("%d",&n); int *a; a=(int *)malloc(sizeof(int)*n); for(int i=0;i<n;i++) a[i]=rand(); for(int i=0;i<n;i++) printf("%d ",a[i]); //Dynamic allocation array a //Random generated array a Elements, outputs /* int n=7; int a[7]={0,-1,20,-4,-100,2000,2001}; for(int i=0;i<n;i++) printf("%d ",a[i]); */ printf("\n"); int middle; middle=selectorder((n-1)/2,a,0,n-1); printf("%d\n",middle); //Find array a Median and assign to middle int *b; b=(int *)malloc(sizeof(int)*n); for(int i=0;i<n;i++) if(a[i]>=middle)b[i]=a[i]-middle; else b[i]=middle-a[i]; //Dynamic allocation array b //array b Medium element=|array a Medium element-middle| int *c; c=(int *)malloc(sizeof(int)*n); for(int i=0;i<n;i++)c[i]=b[i]; //array c Medium element=array b Medium element int k; scanf("%d",&k); //input k int last; last=selectorder(k-1,b,0,n-1); //Find array b pass the civil examinations k Small elements are assigned to last for(int i=0;i<n;i++) if(c[i]<=last)printf("%d ",a[i]); //foreach c,If array c Medium element less than last, //Then output the array at the corresponding position a Elements printf("\n"); sord(a,0,n-1); for(int i=0;i<n;i++)printf("%d ",a[i]); return 0; }