forked from Adoby7/CLRS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrandomized-select-iterative.cpp
67 lines (59 loc) · 1.49 KB
/
randomized-select-iterative.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*************************************************************************
> File Name: randomized-select-iterative.cpp
> Author: Louis1992
> Mail: [email protected]
> Blog: http://gzc.github.io
> Created Time: Sun May 24 11:46:39 2015
************************************************************************/
#include<iostream>
using namespace std;
class Solution {
int partition(int arr[], int l, int r)
{
int x = arr[r], i = l;
for(int j = l; j <= r - 1; j++)
{
if (arr[j] <= x)
{
swap(arr[i], arr[j]);
i++;
}
}
swap(arr[i], arr[r]);
return i;
}
int randomPartition(int arr[], int l, int r)
{
int n = r-l+1;
int pivot = rand() % n;
swap(arr[l + pivot], arr[r]);
return partition(arr, l, r);
}
public:
int kthSmallest(int arr[], int l, int r, int k)
{
cout << l << " " << r << " " << k << endl;
while (k > 0 && k <= r - l + 1)
{
int pos = randomPartition(arr, l, r);
if (pos-l == k-1)
return arr[pos];
else if(pos-l > k-1)
{
r = pos-1;
}
else
{
l = pos+1;
k = k-pos+l-1;
}
}
return INT_MAX;
}
};
int main()
{
int arr[5] = {2,4,1,-2,8};
Solution s;
cout << s.kthSmallest(arr, 0, 4, 2);
}