/* ****************************************************************************** * file name : cb_sort.h * author : Hung Q. Ngo * description: implementations of template versions of randomized quick sort * and insertion sort with a comparison callback ****************************************************************************** */ #include #include // for rand() and srand() #include // for time() /** * ----------------------------------------------------------------------------- * -1 if a < b, 0 if a==b, 1 if a>b * ----------------------------------------------------------------------------- */ template int default_cmp(Item_Type a, Item_Type b) { return a < b? -1 : a == b ? 0 : 1; } /** * ----------------------------------------------------------------------------- * Template Insertion Sort * for each i from 1 to n-1, insert vec[i] to the right place in the prefix * ----------------------------------------------------------------------------- */ template void insertion_sort(std::vector &vec, int (*cmp)(Item_Type, Item_Type) = default_cmp) { Item_Type temp; int j; for (int i=1; i' while (j >= 0 && cmp(vec[j],temp) > 0) { vec[j+1] = vec[j]; j--; } vec[j+1] = temp; } } /** * ----------------------------------------------------------------------------- * 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); }