# 32.2 Quick Select

Dissatisfied with the result that Quicksort is unable to completely defeat Mergesort and truly claim the title for "fastest comparison-based sorting" algorithm, let's shoot our one last shot to overturn the result: use Quick Select to identify the median.&#x20;

## Quick Select Algorithm

Goal: find the median using partioning.&#x20;

Key idea: Median of an length n array will be around index n /2.

1. Initialize array with the leftmost item as the pivot.&#x20;

<figure><img src="/files/6dt1mY8w4g4L74l2k6Cj" alt=""><figcaption><p>Initial Array</p></figcaption></figure>

For this example, the index of the median should be 9 / 2 = 4.&#x20;

2. Partition around pivot.&#x20;

<figure><img src="/files/saxcs3xx5aUSlO1k39e0" alt=""><figcaption><p>Pivot lands at index 2</p></figcaption></figure>

Since the pivot is at index 2, which is not the median. Therefore, need to continue. However, will only partition the **right** subproblem because median can't be to the left! (index n/2 > 2)

3. Partition the subproblem. Repeat the process.

<figure><img src="/files/MZ2s7h0zs6yIfwOtPBUK" alt=""><figcaption></figcaption></figure>

Pivot is at index 6, which means that it is not at the median. Continue.&#x20;

4. Stop when the pivot is at the median index.&#x20;

<figure><img src="/files/poGV8yxDyEwkDrEC83Ez" alt=""><figcaption></figcaption></figure>

Since pivot is at index 4, we are done.&#x20;

## Quick Select Performance

### Worst Case Runtime

The worst case is when the array is in sorted order, which yields a runtime of $$\theta(N^2)$$.

![](/files/400afku3BgagpnYn9vOo)

### Expected Runtime

The expected runtime for the Quick Select Algorithm is $$\theta(N)$$. Here's an intuitive diagram that justifies this result:&#x20;

<figure><img src="/files/GdbN5rlQOjGMJqOouNL3" alt=""><figcaption></figcaption></figure>

Using one of our favorite sums, we can see the runtime is:

$$
N + N/2 + N/4 +.... + 1 = \theta(N)
$$

## Compared to MergeSort?

Unfortunately, even using Quickselect to find the exact median, the resulting algorithm is still quite slow.&#x20;

Team Mergesort wins, sadly.&#x20;


---

# 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/32.-more-quick-sort-sorting-summary/32.2-quick-select.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.
