diff --git a/Sorting algo/Quick sort.cpp b/Sorting algo/Quick sort.cpp new file mode 100644 index 0000000..ca4226f --- /dev/null +++ b/Sorting algo/Quick sort.cpp @@ -0,0 +1,41 @@ +#include +#include + +// Partition function for Quick Sort +int partition(std::vector& arr, int low, int high) { + int pivot = arr[high]; // Select the pivot element + int i = low - 1; + + for (int j = low; j < high; j++) { + if (arr[j] < pivot) { + i++; + std::swap(arr[i], arr[j]); + } + } + std::swap(arr[i + 1], arr[high]); + return i + 1; +} + +// Quick Sort recursive function +void quickSort(std::vector& arr, int low, int high) { + if (low < high) { + int pi = partition(arr, low, high); + + quickSort(arr, low, pi - 1); // Recursively sort left half + quickSort(arr, pi + 1, high); // Recursively sort right half + } +} + +// Main function to test the Quick Sort algorithm +int main() { + std::vector arr = {10, 7, 8, 9, 1, 5}; + int n = arr.size(); + quickSort(arr, 0, n - 1); + + std::cout << "Sorted array: "; + for (int num : arr) { + std::cout << num << " "; + } + return 0; +} + diff --git a/Sorting algo/README.md.txt b/Sorting algo/README.md.txt new file mode 100644 index 0000000..aefe7e4 --- /dev/null +++ b/Sorting algo/README.md.txt @@ -0,0 +1,18 @@ +# Quick Sort Algorithm + +## Overview +Quick Sort is a divide-and-conquer sorting algorithm. It works by selecting a pivot element and partitioning the array around the pivot such that elements less than the pivot are on the left, and elements greater are on the right. The algorithm then recursively applies the same process to the subarrays. + +## Time Complexity +- Best Case: **O(n log n)** - Occurs when the pivot divides the array into two nearly equal halves. +- Average Case: **O(n log n)** - Expected on average for a randomly ordered array. +- Worst Case: **O(n^2)** - Occurs when the pivot selection consistently produces one-sided splits, such as with a sorted array. + +## Space Complexity +- Space Complexity: **O(log n)** - For the recursive call stack in the best and average cases. However, it can go up to **O(n)** in the worst case due to unbalanced partitions. + +## How to Run +Compile and run `quick_sort.cpp` using a C++ compiler: +```bash +g++ quick_sort.cpp -o quick_sort +./quick_sort