diff --git a/sorting/README.md b/sorting/README.md index 91a7bcda..2a904dd7 100644 --- a/sorting/README.md +++ b/sorting/README.md @@ -13,6 +13,7 @@ 9. [Radix Sort](c-or-cpp/radix-sort.cpp) 10. [Shell Sort](c-or-cpp/shell-sort.cpp) 11. [Comb Sort](c-or-cpp/comb-sort.cpp) +12. [3 Way Quick Sort](c-or-cpp/3way_quick_sort.cpp) diff --git a/sorting/c-or-cpp/3way_quick_sort.cpp b/sorting/c-or-cpp/3way_quick_sort.cpp new file mode 100644 index 00000000..b2518773 --- /dev/null +++ b/sorting/c-or-cpp/3way_quick_sort.cpp @@ -0,0 +1,58 @@ +#include +#include +#include + +using std::vector; +using std::swap; + +void partition(vector &a, int l, int r, int &i, int &j) { + if (r - l <= 1){ + if (a[r] < a[l]) + swap (a[r], a[l]); + + i = l; + j = r; + return; + } + + int m = l; + int pivot = a[r]; + + while (m <= r) { + if (a[m] < pivot) + swap(a[l++], a[m++]); + else if (a[m] == pivot) + m++; + else { + swap (a[r--], a[m]); + } + i = l-1; + j = m; + } +} + +void quickSort(vector &a, int l, int r) { + if (l >= r) { + return; + } + + int k = l +(r - l)/2; + int i, j; + partition(a, l, r, i, j); + quickSort(a, l, i); + quickSort(a, j, r); +} + +int main() { + int n; + std::cin >> n; + vector a(n); + for (size_t i = 0; i < a.size(); ++i) { + std::cin >> a[i]; + } + //randomized_quick_sort(a, 0, a.size() - 1); + quickSort(a, 0, a.size()-1); + for (size_t i = 0; i < a.size(); ++i) { + std::cout << a[i] << ' '; + } +}