Add 3way quick sort for c++ (#85)

* Add 3way quick sort for c++

* Include description for 3way_quick_sort
pull/98/head
truonggiangtran 2021-03-04 02:55:27 +08:00 committed by GitHub
parent e375a9f8b0
commit 327a2ad594
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 59 additions and 0 deletions

View File

@ -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)

View File

@ -0,0 +1,58 @@
#include <iostream>
#include <vector>
#include <cstdlib>
using std::vector;
using std::swap;
void partition(vector<int> &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<int> &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<int> 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] << ' ';
}
}