Guest User

Untitled

a guest
Jun 19th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. K-th order statistic in O (N)
  2.  
  3. Suppose we are given an array A of length N, and suppose given the number of K. The challenge is to find in the array K-th largest number, ie K-th order statistics.
  4.  
  5.  
  6.  
  7. The basic idea - the idea of ​​using quicksort. Actually, the algorithm is simple, difficult to prove that he works an average of O (N), in contrast to the quick sort.
  8.  
  9.  
  10.  
  11. The implementation in the form of non-recursive function:
  12.  
  13. template <class T>
  14. T order_statistics (std :: vector <T> a, unsigned n, unsigned k)
  15. {
  16. using std :: swap;
  17. for (unsigned l = 1, r = n;;)
  18. {
  19.  
  20. if (r <= l +1)
  21. {
  22. / / The current part consists of one or two elements -
  23. / / Can easily find the answer
  24. if (r == l +1 && a [r] <a [l])
  25. swap (a [l], a [r]);
  26. return a [k];
  27. }
  28.  
  29. / / Sort a [l], a [l +1], a [r]
  30. unsigned mid = (l + r) >> 1;
  31. swap (a [mid], a [l +1]);
  32. if (a [l]> a [r])
  33. swap (a [l], a [r]);
  34. if (a [l +1]> a [r])
  35. swap (a [l +1], a [r]);
  36. if (a [l]> a [l +1])
  37. swap (a [l], a [l +1]);
  38.  
  39. / / Do the division
  40. / / Barrier is a [l +1], ie the median of a [l], a [l +1], a [r]
  41. unsigned
  42. i = l +1,
  43. j = r;
  44. const T
  45. cur = a [l +1];
  46. for (; ;)
  47. {
  48. while (a [+ + i] <cur);
  49. while (a [- j]> cur);
  50. if (i> j)
  51. break;
  52. swap (a [i], a [j]);
  53. }
  54.  
  55. / / Insert a barrier
  56. a [l +1] = a [j];
  57. a [j] = cur;
  58.  
  59. / / Continue to work in that part
  60. / / Which should contain the desired element
  61. if (j> = k)
  62. r = j-1;
  63. if (j <= k)
  64. l = i;
  65.  
  66. }
  67. }
Add Comment
Please, Sign In to add comment