> For the complete documentation index, see [llms.txt](https://docs.1l.lol/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.1l.lol/sorting/quick-sort.md).

# 快速排序

### 分治思想

快速排序选取一个**基准值（pivot）**，把数组分成“小于基准”和“大于基准”两部分，再分别递归排序。

### 时间复杂度

平均 **O(n log n)**，最坏 O(n²)（如对已排序数组取端点作基准）；**不稳定**。

```cpp
void quickSort(int a[], int l, int r) {
    if (l >= r) return;
    int pivot = a[(l + r) / 2];
    int i = l, j = r;
    while (i <= j) {
        while (a[i] < pivot) i++;
        while (a[j] > pivot) j--;
        if (i <= j) { swap(a[i], a[j]); i++; j--; }
    }
    quickSort(a, l, j);
    quickSort(a, i, r);
}
```

### 与归并排序对比

|     | 快速排序       | 归并排序       |
| --- | ---------- | ---------- |
| 平均  | O(n log n) | O(n log n) |
| 最坏  | O(n²)      | O(n log n) |
| 空间  | O(log n)   | O(n)       |
| 稳定性 | 不稳定        | 稳定         |

### 实践建议

平时可直接用标准库 `sort`（底层为混合排序），自己实现则要注意基准选取，避免退化。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.1l.lol/sorting/quick-sort.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
