# 30.2 Quicksort Algorithm

The figure below shows a partition performed on the pivot of 5. Notice how 5 in its “proper place” (in other words, it’s exactly where it should be if the entire array was sorted).

This suggests that the partition procedure can be used recursively on the two halves to the left and to the right of the pivot element.&#x20;

<figure><img src="https://lh6.googleusercontent.com/ZMiWPSUmOc95h-fBaxMB4I42Djyk0uAL_s8J9XwwqW4KHizpn1xf0wuwciRKa033jyMKK78Vul99b1xYa_fLUOVYFnFhLNZDZstdWSLv-M6Z84H_QD2YOmHeJGjsPOaxIlGWojDANKOPLZ3tVORvZQQ" alt=""><figcaption><p>After partitioning on the pivot element of 5, 5 is in the “proper place” and there are two halves left to be sorted. The left half are the four elements of [3, 2, 1, 4], and the right half consists of the three elements of [7, 8, 6]. </p></figcaption></figure>

The properties that partitioning provides inspires Tony Hoare’s Quicksort algorithm.&#x20;

**Quicksort Algorithm**&#x20;

To quicksort N items:&#x20;

1. Partition on the leftmost item as the pivot.&#x20;
2. Recursively quicksort the left half.&#x20;
3. Recursively quicksort the right half.&#x20;

<figure><img src="https://lh6.googleusercontent.com/srbltrmdQThh9xwjjq-smTXOAVhav1ISWHf4eKX2yZlHr50kHlvZDmH36nNMwLWuMkOlzyApaJWvUdEA1ydHDYKbulYtVuqU6kOn9QbMWAraIOcQae7ymka3zCJKcgzd0u9SeubYP7as_PnnRnEU6Ak" alt=""><figcaption><p><a href="https://docs.google.com/presentation/d/1QjAs-zx1i0_XWlLqsKtexb-iueao9jNLkN-gW9QxAD0/edit?usp=sharing">Demo of quicksort is linked here</a></p></figcaption></figure>

<br>


---

# Agent Instructions: 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:

```
GET https://cs61b-2.gitbook.io/cs61b-textbook/30.-quicksort/30.2-quicksort-algorithm.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
