fork download
  1. // selects the median of medians in an array
  2. int select(int *a, int s, int e, int k){
  3. // if the partition length is less than or equal to 5
  4. // we can sort and find the kth element of it
  5. // this way we can find the median of n/5 partitions
  6. if(e-s+1 <= 5){
  7. sort(a+s, a+e);
  8. return s+k-1;
  9. }
  10.  
  11. // if array is bigger
  12. // we partition the array in subarrays of size 5
  13. // no. of partitions = n/5 = (e+1)/5
  14. // iterate through each partition
  15. // and recursively calculate the median of all of them
  16. // and keep putting the medians in the starting of the array
  17. for(int i=0; i<(e+1)/5; i++){
  18. int left = 5*i;
  19. int right = left + 4;
  20. if(right > e) right = e;
  21. int median = select(a, 5*i, 5*i+4, 3);
  22. swap(a[median], a[i]);
  23. }
  24.  
  25. // now we have array
  26. // a[0] = median of 1st 5 sized partition
  27. // a[1] = median of 2nd 5 sized partition
  28. // and so on till n/5
  29. // to find out the median of these n/5 medians
  30. // we need to select the n/10th element of this set (i.e. middle of it)
  31. return select(a, 0, (e+1)/5, (e+1)/10);
  32. }
  33.  
  34. int main(){
  35. int a[] = {6,7,8,1,2,3,4,5,9,10};
  36. int n = 10;
  37.  
  38. int mom = select(a, 0, n-1, n/2);
  39. cout<<"Median of Medians: " << a[mom] << endl;
  40. return 0;
  41. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
7
23
11
compilation info
prog.c: In function ‘select’:
prog.c:7:9: warning: implicit declaration of function ‘sort’ [-Wimplicit-function-declaration]
         sort(a+s, a+e);
         ^~~~
prog.c:22:9: warning: implicit declaration of function ‘swap’ [-Wimplicit-function-declaration]
         swap(a[median], a[i]);
         ^~~~
prog.c: In function ‘main’:
prog.c:39:5: error: ‘cout’ undeclared (first use in this function)
     cout<<"Median of Medians: " << a[mom] << endl;
     ^~~~
prog.c:39:5: note: each undeclared identifier is reported only once for each function it appears in
prog.c:39:46: error: ‘endl’ undeclared (first use in this function)
     cout<<"Median of Medians: " << a[mom] << endl;
                                              ^~~~
stdout
Standard output is empty