> For the complete documentation index, see [llms.txt](https://tanias-workspace.gitbook.io/tanias-little-corner/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://tanias-workspace.gitbook.io/tanias-little-corner/algorithms/quick-sort.md).

# Quick Sort

Quick Sort is a divide-and-conquer algorithm that selects a 'pivot' element, partitions the array into elements less than and greater than the pivot, and recursively sorts the sub-arrays.

**Steps**:

1. Choose a pivot element.
2. Partition the array into elements less than and greater than the pivot.
3. Recursively apply the same procedure to the sub-arrays.

<figure><img src="/files/6AdaixWFUQq77XMJGn5a" alt="" width="375"><figcaption></figcaption></figure>

```cpp
#include <vector>
#include <iostream>

int partition(std::vector<int> &arr, int low, int high) {
    int pivot = arr[high];
    int i = (low - 1);
    for (int j = low; j <= high - 1; j++) {
        if (arr[j] < pivot) {
            i++;
            std::swap(arr[i], arr[j]);
        }
    }
    std::swap(arr[i + 1], arr[high]);
    return (i + 1);
}

void quickSort(std::vector<int> &arr, int low, int high) {
    if (low < high) {
        int pi = partition(arr, low, high);
        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}

int main() {
    std::vector<int> arr = {64, 34, 25, 12, 22, 11, 90};
    quickSort(arr, 0, arr.size() - 1);
    for (int num : arr) std::cout << num << " ";
    return 0;
}

```

**Quick Sort**: Efficient and commonly used, with an average time complexity of O(n log⁡ n), but can degrade to O(n^2) in the worst case.
