> For the complete documentation index, see [llms.txt](https://wiki.hanzheteng.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://wiki.hanzheteng.com/algorithm/cs/sorting.md).

# Sorting

### Selection Sort

* О(n^2) comparisons, О(n) swaps
* naive implementation for sorting

### Insertion Sort

* О(n^2) comparisons and swaps
* O(1) auxiliary space
* can run online
* stable

### Merge Sort

* O(n log(n)) by divide and conquer
* O(n) auxiliary space
* stable; deterministic

### Quick Sort

* O(n log(n)) by divide and conquer; worst case O(n) though
* O(1) auxiliary space; one of exchange sorts (cf. bubble sort)
* unstable; randomized

### Introsort

* hybrid sorting algorithm
* derived from quicksort, heapsort, and insertion sort
* unstable

### Timsort

* hybrid sorting algorithm
* derived from merge sort and insertion sort
* stable

### Distribution Sort

* O(n+m) non-comparative sorting algorithms: radix sort, bucket sort, digital sort, pigeonhole sort
* it avoids comparison by creating and distributing elements into buckets according to their radix
* the lower bound for comparative sorting algorithm is O(n log(n)); in certain cases, non-comparative sorting can do better, e.g., O(n)

### Topological Sort

* for directed acyclic graph (DAG)
* output a linear ordering of its vertices&#x20;

### Tree Sort

* builds a binary search tree from the elements to be sorted, and then traverses the tree (in-order) so that the elements come out in sorted order.
* Its typical use is sorting elements online: after each insertion, the set of elements seen so far is available in sorted order.


---

# 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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://wiki.hanzheteng.com/algorithm/cs/sorting.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
