Skip to content

Commit 4c92e34

Browse files
Update Quickselect for Finding the k-th Smallest Element.cpp
1 parent adf3583 commit 4c92e34

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

search/Quickselect for Finding the k-th Smallest Element.cpp

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
#include <bits/stdc++.h>
1+
#include <iostream>
2+
#include <vector>
23
using namespace std;
34

45
int partition(vector<int>& arr, int left, int right) {
@@ -30,8 +31,27 @@ int quickSelect(vector<int>& arr, int left, int right, int k) {
3031
}
3132

3233
int main() {
33-
vector<int> arr = {3, 2, 1, 5, 6, 4};
34-
int k = 2;
34+
vector<int> arr;
35+
int n, k;
36+
37+
cout << "Enter the number of elements in the array: ";
38+
cin >> n;
39+
40+
cout << "Enter the elements of the array: ";
41+
for (int i = 0; i < n; ++i) {
42+
int num;
43+
cin >> num;
44+
arr.push_back(num);
45+
}
46+
47+
cout << "Enter the value of k (to find the k-th smallest element): ";
48+
cin >> k;
49+
50+
if (k < 1 || k > n) {
51+
cout << "Invalid value of k. Please enter a value between 1 and " << n << "." << endl;
52+
return 1; // Exit with error code
53+
}
54+
3555
cout << k << "-th smallest element is " << quickSelect(arr, 0, arr.size() - 1, k - 1) << endl;
3656
return 0;
3757
}

0 commit comments

Comments
 (0)