/* ****************************************************************************** * file name : templ_sort.h * author : Hung Q. Ngo * description: implementation a template version of randomized quick sort * and insertion sort ****************************************************************************** */ #include #include // for rand() and srand() #include // for time() /** * ----------------------------------------------------------------------------- * 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) { Item_Type temp, j; for (int i=1; i' with Item_Type while (j >= 0 && vec[j] > temp) { 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) { 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) { std::srand(static_cast(std::time(0))); rqs_with_range(vec, 0, vec.size()-1); }