1
1
#include < iostream>
2
2
#include < vector>
3
+ #include < algorithm>
4
+
3
5
using namespace std ;
4
6
7
+ // Function to partition the array and return the pivot index
5
8
int partition (vector<int >& arr, int left, int right) {
6
9
int pivot = arr[right];
7
10
int i = left;
@@ -16,40 +19,29 @@ int partition(vector<int>& arr, int left, int right) {
16
19
return i;
17
20
}
18
21
22
+ // Function to find the k-th smallest element using QuickSelect
19
23
int quickSelect (vector<int >& arr, int left, int right, int k) {
20
- if (left == right) return arr[left];
24
+ if (left == right) return arr[left]; // Base case: only one element
21
25
22
26
int pivotIndex = partition (arr, left, right);
23
27
24
28
if (k == pivotIndex) {
25
- return arr[k];
29
+ return arr[k]; // Found the k-th smallest element
26
30
} else if (k < pivotIndex) {
27
- return quickSelect (arr, left, pivotIndex - 1 , k);
31
+ return quickSelect (arr, left, pivotIndex - 1 , k); // Search left
28
32
} else {
29
- return quickSelect (arr, pivotIndex + 1 , right, k);
33
+ return quickSelect (arr, pivotIndex + 1 , right, k); // Search right
30
34
}
31
35
}
32
36
33
37
int main () {
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;
38
+ vector<int > arr = {3 , 2 , 1 , 5 , 6 , 4 };
39
+ int k = 2 ; // We want the 2nd smallest element
49
40
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
41
+ // Input validation for k
42
+ if (k < 1 || k > arr.size ()) {
43
+ cout << " Error: k must be between 1 and " << arr.size () << endl;
44
+ return -1 ;
53
45
}
54
46
55
47
cout << k << " -th smallest element is " << quickSelect (arr, 0 , arr.size () - 1 , k - 1 ) << endl;
0 commit comments