/* ****************************************************************************** * file name : better_rqs.cpp * author : Hung Q. Ngo * description: a minor twist to the randomized quick sort algorithm which * makes it run faster on inputs where the item values belong * to a small finite class ****************************************************************************** */ #include #include #include // for rand() and srand() #include // for time() using namespace std; /** * * ----------------------------------------------------------------------------- * print a vector of Item_Type, finish with a new line * assumes compiler knows how to cout << Item_Type * * ----------------------------------------------------------------------------- */ template void print_vec(vector& vec) { for (int i=0; ib * ----------------------------------------------------------------------------- */ template int default_cmp(Item_Type a, Item_Type b) { return a < b? -1 : a == b ? 0 : 1; } /** * ----------------------------------------------------------------------------- * The Randomized Quick Sort algorithm * - pick a random pivot, that's all * ----------------------------------------------------------------------------- */ template void rqs_with_range(std::vector &vec, int p, int q, int (*cmp)(Item_Type, Item_Type)) { if (p >= q) return; // pick a random pivot int m = std::rand() % (q-p+1); std::swap(vec[q], vec[p+m]); // partition int r=p-1; for (int j=p; j void randomized_quick_sort(std::vector &vec, int (*cmp)(Item_Type, Item_Type) = default_cmp) { std::srand(static_cast(std::time(0))); rqs_with_range(vec, 0, vec.size()-1, cmp); } /** * ----------------------------------------------------------------------------- * returns a random vector of n elements, each from 0 to k-1 * ----------------------------------------------------------------------------- */ vector random_vector(size_t n, size_t k) { srand(static_cast(time(0))); vector ret(n); for (int i=0; i vec = random_vector(50000, 2); cout << "Before: "; print_vec(vec); randomized_quick_sort(vec); cout << "After: "; print_vec(vec); }