11#include < iostream>
22#include < vector>
3+ #include < algorithm>
4+
35using namespace std ;
46
7+ // Function to partition the array and return the pivot index
58int partition (vector<int >& arr, int left, int right) {
69 int pivot = arr[right];
710 int i = left;
@@ -16,40 +19,29 @@ int partition(vector<int>& arr, int left, int right) {
1619 return i;
1720}
1821
22+ // Function to find the k-th smallest element using QuickSelect
1923int 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
2125
2226 int pivotIndex = partition (arr, left, right);
2327
2428 if (k == pivotIndex) {
25- return arr[k];
29+ return arr[k]; // Found the k-th smallest element
2630 } else if (k < pivotIndex) {
27- return quickSelect (arr, left, pivotIndex - 1 , k);
31+ return quickSelect (arr, left, pivotIndex - 1 , k); // Search left
2832 } else {
29- return quickSelect (arr, pivotIndex + 1 , right, k);
33+ return quickSelect (arr, pivotIndex + 1 , right, k); // Search right
3034 }
3135}
3236
3337int 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
4940
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 ;
5345 }
5446
5547 cout << k << " -th smallest element is " << quickSelect (arr, 0 , arr.size () - 1 , k - 1 ) << endl;
0 commit comments