From ac2b7fd5f67e2216e432e9f80ed35b9f1d1a584c Mon Sep 17 00:00:00 2001 From: HeYPoonam <115446295+HeYPoonam@users.noreply.github.com> Date: Thu, 13 Oct 2022 19:56:28 +0530 Subject: [PATCH] Create quickSort.cpp --- quickSort.cpp | 70 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 quickSort.cpp diff --git a/quickSort.cpp b/quickSort.cpp new file mode 100644 index 0000000..653e910 --- /dev/null +++ b/quickSort.cpp @@ -0,0 +1,70 @@ + +#include +using namespace std; + +int partition(int arr[], int start, int end) +{ + + int pivot = arr[start]; + + int count = 0; + for (int i = start + 1; i <= end; i++) { + if (arr[i] <= pivot) + count++; + } + + int pivotIndex = start + count; + swap(arr[pivotIndex], arr[start]); + + + int i = start, j = end; + + while (i < pivotIndex && j > pivotIndex) { + + while (arr[i] <= pivot) { + i++; + } + + while (arr[j] > pivot) { + j--; + } + + if (i < pivotIndex && j > pivotIndex) { + swap(arr[i++], arr[j--]); + } + } + + return pivotIndex; +} + +void quickSort(int arr[], int start, int end) +{ + + + if (start >= end) + return; + + + int p = partition(arr, start, end); + + // Sorting the left part + quickSort(arr, start, p - 1); + + // Sorting the right part + quickSort(arr, p + 1, end); +} + +int main() +{ + + int arr[] = { 9, 3, 4, 2, 1, 8 }; + int n = 6; + + quickSort(arr, 0, n - 1); + + for (int i = 0; i < n; i++) { + cout << arr[i] << " "; + } + + return 0; +}