-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKthSmallestElement.cpp
More file actions
71 lines (60 loc) · 1.43 KB
/
KthSmallestElement.cpp
File metadata and controls
71 lines (60 loc) · 1.43 KB
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
68
69
70
71
#include <vector>
#include <iostream>
#include <cstdlib>
class SmallestElementComputer
{
private:
int partition(std::vector<int>& arr, int left, int right, int pivIndex)
{
std::swap(arr[pivIndex], arr[right]);
int pivot = arr[right];
int greaterThanPivot = left;
int smallerThanPivot = right - 1;
while (greaterThanPivot <= smallerThanPivot)
{
if (arr[greaterThanPivot] > pivot && arr[smallerThanPivot] < pivot)
{
std::swap(arr[greaterThanPivot], arr[smallerThanPivot]);
--smallerThanPivot;
++greaterThanPivot;
} else if (arr[greaterThanPivot] < pivot) {
++greaterThanPivot;
} else {
--smallerThanPivot;
}
}
std::swap(arr[greaterThanPivot], arr[right]);
return greaterThanPivot;
}
int select(std::vector<int>& arr, int left, int right, int k)
{
if (left == right)
return arr[left];
int pivot = left + std::rand() % (left - right + 1);
pivot = partition(arr, left, right, pivot);
if (k == pivot)
return arr[k];
if (k < pivot)
{
// Look to left
return select(arr, left, pivot - 1, k);
} else {
// Look to right
return select(arr, pivot + 1, right, k);
}
}
public:
int find(int k, std::vector<int> arr)
{
return select(arr, 0, arr.size() - 1, k);
}
};
int main()
{
std::vector<int> arr{ 7,4,6,3,9,1 };
int k = 2;
SmallestElementComputer obj;
int element = obj.find(k, arr);
std::cout << k << "th smallest element is " << element << std::endl;
return 0;
}