Quick Select in C++
Quickselect with std::vector
#include <iostream> #include <vector> #include <assert.h> using namespace std; void swap(vector<int>& list, int l, int r) { if (l == r) return; int t= list[l]; list[l]= list[r]; list[r]= t; } void median3(vector<int>& list, int l, int r) { if (l == r) return; int m= (l+r)/2; if (list[l] > list[r]) swap(list, l, r); // r has bigger number if (list[m] > list[r]) return; // r is the median of 3 else { if (list[l] > list[m]) swap(list, l, r); else swap(list, m, r); } } int select_k(vector<int>& list, int l, int r, int k) { if (l == r) { assert(l == k); return list[l]; } median3(list, l, r); int i= l; int j= r-1; while (i <= j) { while (i <= j && list[i] <= list[r]) i++; // left will include values less than or equal to pivot while (i <= j && list[j] > list[r]) j--; if (i < j) { swap(list, i, j); i++; j--; } } if (list[i] > list[r]) { swap(list, i, r); if (i == k) return list[i]; else if (k < i) return select_k(list, l, i-1, k); else return select_k(list, i+1, r, k); } else { if (r == k) return list[r]; else return select_k(list, l, r-1, k); } } int select_k(vector<int>& list, int k) { int val= select_k(list, 0, list.size()-1, k); return val; } int main() { vector<int> list; for (int i= 0; i < 10; ++i) { int val= i*2%3; cout << val << " "; list.push_back(val); } cout << endl; for (int k= 0; k < 10; ++k) cout << k << ": " << select_k(list, k) << endl; //cout << "6: " << select_k(list, 6) << endl; return 0; }