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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| #include<algorithm> #include<cassert> #include<iostream> #include<vector>
namespace quick_sort{ template <typename T> int partition(std::vector<T> *arr, const int &low, const int &high) { T pivot = (*arr)[high]; int i = (low - 1);
for (int j = low; j < high; j++) { if ((*arr)[j] <= pivot) { i++; std::swap((*arr)[i], (*arr)[j]); } }
std::swap((*arr)[i + 1], (*arr)[high]); return (i + 1); }
template <typename T> void quick_sort(std::vector<T> *arr, const int &low, const int &high) { if (low < high) { int p = partition(arr, low, high);
quick_sort(arr, low, p - 1); quick_sort(arr, p + 1, high); } }
template <typename T> std::vector<T> quick_sort(std::vector<T> arr, const int &low, const int &high) { if (low < high) { int p = partition(&arr, low, high);
quick_sort(&arr, low, p - 1); quick_sort(&arr, p + 1, high); } return arr; }
template <typename T> void show(const std::vector<T> &arr, const int &size) { for (int i = 0; i < size; i++) std::cout << arr[i] << " "; std::cout << "\n"; } }
int main(){ std::vector<uint64_t> arr = {5, 3, 8, 12, 14, 16, 28, 96, 2, 5977}; std::vector<uint64_t> arr_sorted = quick_sort::quick_sort( arr, 0, int(std::end(arr) - std::begin(arr)) - 1);
assert(std::is_sorted(std::begin(arr_sorted), std::end(arr_sorted))); std::cout << "\n1st test: passed!\n";
std::cout << "1st array:\n"; ::quick_sort::show(arr_sorted, std::end(arr) - std::begin(arr)); std::cout << std::endl; }
|