> 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/basic-sorts.md).

# 冒泡、插入、选择排序

### 冒泡排序

相邻两两比较，大的往后“冒泡”。稳定。时间复杂度 O(n²)。

```cpp
void bubbleSort(int a[], int n) {
    for (int i = 0; i < n - 1; i++) {
        bool swapped = false;
        for (int j = 0; j < n - 1 - i; j++)
            if (a[j] > a[j + 1]) { swap(a[j], a[j + 1]); swapped = true; }
        if (!swapped) break;   // 已有序，提前结束
    }
}
```

### 选择排序

每轮选出最小值放到前面。**不稳定**。O(n²)。

```cpp
void selectSort(int a[], int n) {
    for (int i = 0; i < n - 1; i++) {
        int pos = i;
        for (int j = i + 1; j < n; j++)
            if (a[j] < a[pos]) pos = j;
        swap(a[i], a[pos]);
    }
}
```

### 插入排序

把元素插入到前面已排好序的部分。稳定。O(n²)，近似有序时接近 O(n)。

```cpp
void insertSort(int a[], int n) {
    for (int i = 1; i < n; i++) {
        int key = a[i], j = i - 1;
        while (j >= 0 && a[j] > key) { a[j + 1] = a[j]; j--; }
        a[j + 1] = key;
    }
}
```

### 三者对比

| 算法 | 稳定性 | 最好    | 最坏    |
| -- | --- | ----- | ----- |
| 冒泡 | 稳定  | O(n)  | O(n²) |
| 选择 | 不稳定 | O(n²) | O(n²) |
| 插入 | 稳定  | O(n)  | O(n²) |


---

# 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/basic-sorts.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.
