From 2704644d571822e47cb23073f07a92737dd7e901 Mon Sep 17 00:00:00 2001 From: Aditya Wadkar <67093170+AdityaWadkar@users.noreply.github.com> Date: Thu, 27 Oct 2022 17:17:11 +0530 Subject: [PATCH] Quick sort using CPP --- quick_Sort.cpp | 79 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 quick_Sort.cpp diff --git a/quick_Sort.cpp b/quick_Sort.cpp new file mode 100644 index 0000000..1997242 --- /dev/null +++ b/quick_Sort.cpp @@ -0,0 +1,79 @@ + + +/* + + Time complexity +Worst complexity: n^2 +Average complexity: n*log(n) +Best complexity: n*log(n) + +Space complexity :- O(n) + +*/ + +#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); + + quickSort(arr, start, p - 1); + + 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; +}