Theory
Implementation in C++
#include <bits/stdc++.h>
using namespace std;
typedef long long int64;
class QuickSelect {
private:
int partition(vector<int>& A, int left, int right, int pivotIndex) {
int pivotValue = A[pivotIndex];
std::swap(A[pivotIndex], A[right-1]);
int nextIndex = left;
for (int i = left; i + 1 < right; i++) {
if (A[i] < pivotValue) {
std::swap(A[nextIndex], A[i]);
nextIndex++;
}
}
std::swap(A[nextIndex], A[right-1]);
return nextIndex;
}
int select(vector<int>& A, int left, int right, int k, std::mt19937& gen) {
if (left + 1 == right) {
return A[left];
}
int size = right - left;
int64 rnd = static_cast<int64>(gen()) % size;
int pivotIndex = left + rnd;
pivotIndex = partition(A, left, right, pivotIndex);
if (k == pivotIndex + 1) {
return A[pivotIndex];
} else if (k < pivotIndex + 1) {
return select(A, left, pivotIndex, k, gen);
}
return select(A, pivotIndex + 1, right, k, gen);
}
public:
int findKthSmallest(vector<int>& nums, int k) {
std::random_device rd;
std::mt19937 gen(rd());
return select(nums, 0, nums.size(), k, gen);
}
};
Practice
Pingback: tizanidine prices
Pingback: wellbutrin sr buy
Pingback: buy diclofenac eye drops
Pingback: promethazine prices
Pingback: prednisone 5mg
Pingback: fluoxetine 10mg
Pingback: lisinopril generic
Pingback: buy benadryl itch stopping cream
Pingback: order hyzaar (losartan + hydrochlorothiazide)
Pingback: cheap metformin
Pingback: new usa casino online real money
Pingback: 21.com casino win real money games
Pingback: the average full price retail of tadalafil 20mg in new hampshire
Pingback: real money casino with no deposit