From 48ed23abb2d77f487ba08ea05c198f6f165772eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Marques?= Date: Thu, 4 Oct 2018 00:32:06 +0100 Subject: [PATCH] quick_sort.cpp adds QuickSort Algorithm Closes https://github.com/NITSkmOS/Algorithms/issues/250 --- quicksort/Cpp/quick_sort.cpp | 42 ++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 quicksort/Cpp/quick_sort.cpp diff --git a/quicksort/Cpp/quick_sort.cpp b/quicksort/Cpp/quick_sort.cpp new file mode 100644 index 00000000..3ac2dbaf --- /dev/null +++ b/quicksort/Cpp/quick_sort.cpp @@ -0,0 +1,42 @@ + +#include + +using std::cout; + +void quick_sort(int a[], int left, int right) { + + int i = left, j = right; + int pivot = a[right]; + + while (i <= j) { + while (a[i] < pivot) + i++; //carry on, this part already sorted + while (a[j] > pivot) + j--; //carry on, this part already sorted + if (i <= j) { // a[i]>=pivot and a[j]<=pivot + //swap a[i] with a[j] + int tmp = a[i]; + a[i] = a[j]; + a[j] = tmp; + i++; + j--; + } + }; + + if (left < j) + quick_sort(a, left, j); + if (i < right) + quick_sort(a, i, right); + +} + +int main(void){ + int a[10] = { 10, 7, 9, 4, 6, 2, 5, 6, 84, 12}; + int a_size = sizeof(a)/sizeof(a[0]); + + quick_sort(a, 0, a_size-1); + + for(int i=0; i