-
-
Notifications
You must be signed in to change notification settings - Fork 7.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create Quickselect for Finding the k-th Smallest Element.cpp
adding Quickselect for Finding the k-th Smallest Element.cpp
- Loading branch information
1 parent
e841605
commit 4d4401e
Showing
1 changed file
with
37 additions
and
0 deletions.
There are no files selected for viewing
37 changes: 37 additions & 0 deletions
37
search/Quickselect for Finding the k-th Smallest Element.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
#include <bits/stdc++.h> | ||
using namespace std; | ||
|
||
int partition(vector<int>& arr, int left, int right) { | ||
int pivot = arr[right]; | ||
int i = left; | ||
|
||
for (int j = left; j < right; ++j) { | ||
if (arr[j] <= pivot) { | ||
swap(arr[i], arr[j]); | ||
i++; | ||
} | ||
} | ||
swap(arr[i], arr[right]); | ||
return i; | ||
} | ||
|
||
int quickSelect(vector<int>& arr, int left, int right, int k) { | ||
if (left == right) return arr[left]; | ||
|
||
int pivotIndex = partition(arr, left, right); | ||
|
||
if (k == pivotIndex) { | ||
return arr[k]; | ||
} else if (k < pivotIndex) { | ||
return quickSelect(arr, left, pivotIndex - 1, k); | ||
} else { | ||
return quickSelect(arr, pivotIndex + 1, right, k); | ||
} | ||
} | ||
|
||
int main() { | ||
vector<int> arr = {3, 2, 1, 5, 6, 4}; | ||
int k = 2; | ||
cout << k << "-th smallest element is " << quickSelect(arr, 0, arr.size() - 1, k - 1) << endl; | ||
return 0; | ||
} |