一个关于线性时间选择(TOP K)的未解之谜

在line19对rand()%(r-p)改成rand()%(r-p+1)陷入了死循环,目前难以理解

 1 int Partition(vector<int> &a, int p, int r)
 2 {
 3     int x = a[p];
 4     int i = p, j = r + 1;
 5     while (1)
 6     {
 7         while (a[++i] < x&&i < r);
 8         while (a[--j] > x);
 9         if (i >= j)
10             break;
11         swap(a[i], a[j]);
12     }
13     a[p] = a[j];
14     a[j] = x;
15     return j;
16 }
17 int RandomizedPartition(vector<int> &a, int p, int r)
18 {
19     int i = rand() % (r - p) + p;
20     cout << i << endl;
21     swap(a[i], a[p]);
22     return Partition(a, p, r);
23 }
24 
25 int RandomizedSelect(vector<int> &a, int p, int r, int k)
26 {
27     cout << p << " " << r << " " << k << endl;
28     for (auto e : a)
29         cout << e << " ";
30     cout << endl;
31     if (p == r)
32         return a[p];
33     int i = RandomizedPartition(a, p, r);
34     int j = i - p + 1;
35     cout << i << " " << j << endl;
36     if (k <= j)
37         RandomizedSelect(a, p, i, k);
38     else
39         RandomizedSelect(a, i + 1, r, k - j);
40 }
41 
42 int main(void)
43 {
44     vector<int> test = { 12,12,4,55,2,5 };
45     cout << RandomizedSelect(test, 0, test.size() - 1, 4);
46     return 0;
47 }

猜你喜欢

转载自www.cnblogs.com/zouma/p/11745370.html