1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| #include <vector> using namespace std;
int dnc(vector<int>& array, int k, int l, int r) { if(l == r) return array[l]; if(l + 1 == r) { if(array[l] > array[r]) swap(array[l], array[r]); return array[k]; } int pivot = array[r]; int left = l, right = r - 1; while(left <= right) { while(left <= right and array[left] < pivot) left++; while(left <= right and array[right] > pivot) right--; if(left <= right and array[left] > array[right]) swap(array[left++], array[right--]); } swap(array[left], array[r]); if(left == k) return array[k]; if(left + 1 <= k) return dnc(array, k, left + 1, r); return dnc(array, k, l, left - 1); }
int quickselect(vector<int> array, int k) { return dnc(array, k - 1, 0, array.size() - 1); }
|