Skip to content

Commit adf3583

Browse files
Create Quickselect for Finding the k-th Smallest Element.cpp
1 parent 136e6c0 commit adf3583

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
int partition(vector<int>& arr, int left, int right) {
5+
int pivot = arr[right];
6+
int i = left;
7+
8+
for (int j = left; j < right; ++j) {
9+
if (arr[j] <= pivot) {
10+
swap(arr[i], arr[j]);
11+
i++;
12+
}
13+
}
14+
swap(arr[i], arr[right]);
15+
return i;
16+
}
17+
18+
int quickSelect(vector<int>& arr, int left, int right, int k) {
19+
if (left == right) return arr[left];
20+
21+
int pivotIndex = partition(arr, left, right);
22+
23+
if (k == pivotIndex) {
24+
return arr[k];
25+
} else if (k < pivotIndex) {
26+
return quickSelect(arr, left, pivotIndex - 1, k);
27+
} else {
28+
return quickSelect(arr, pivotIndex + 1, right, k);
29+
}
30+
}
31+
32+
int main() {
33+
vector<int> arr = {3, 2, 1, 5, 6, 4};
34+
int k = 2;
35+
cout << k << "-th smallest element is " << quickSelect(arr, 0, arr.size() - 1, k - 1) << endl;
36+
return 0;
37+
}

0 commit comments

Comments
 (0)