---
title: "QuickSort"
format:
html:
toc: true
number-sections: true
code-line-numbers: true
---
[In-class notes](hand_written_notes/QuickSort5.pdf)
## Learning Goals
- Describe QuickSort and Partition
- Benchmark worst-case (unlucky) and best-case (lucky) QuickSort runtimes
- Define and understand key probability terms: "sample space," "random variable," "expectation value," "linearity of expectation."
- Describe processes (brute force, clever) for calculating the average runtime of algorithms
- Analyze number of comparisons done in QuickSort and use to calculate the average runtime of QuickSort
- Describe advantages of different sorting algorithms
## QuickSort
> **QuickSort(A):**
>
> // Input: Array $A$ of unique integers
> // Output: Sorted $A$
>
> // Base Case
> If $|A|=1$: Return $A$
>
> // Preprocessing and Dividing
> $pivInd \leftarrow$ randomly chosen index of $A$
> Partition($A$, $pivInd$, $A[pivInd]$) // Modifies $A$ to have form $[A_L, pivVal,A_R]$
>
> // Conquer
> QuickSort($A_L$)
> QuickSort($A_R$)
The key subroutine in QuickSort is called Partition
> **Partition(A, pivInd, pivVal):**
>
> // Input: Array $A$ of unique integers, an pivot element with index pivInd and value pivVal
> // Output: An array containing the same values as $A$, such that all elements with values less than pivVal occur first in the array, and then pivVal is the next element in the array, and then all elements with
values more than pivVal occur next.
>
> Swap positions: (pivot element) $\leftrightarrow$ $(A[1])$
> $current\leftarrow 2$
> While $current \leq |A|$:
> $\quad$ If $A[current] $\qquad$ Swap positions $(A[current])\leftrightarrow$(pivot element)
> $\qquad$ Swap positions $(A[pivInd+1])\leftrightarrow$(pivot element)
> $\quad current\leftarrow current +1$
Our goal in this unit will be to analyze the average runtime of **QuickSort**. How to do this?
- Notice that the **Partition** subroutine takes up the most time in each recursive call.
- Also notice that the runtime of **Partition** scales asymptotically with the number of times we do the comparison
$$\textrm{If }A[current]i,j$
2) What values can $X_{i,j}$ take (only 2 are possible) and under which conditions does it take each value?
3) What is the probability of $z_i,$ $z_j$ being compared
What is the probability that $X_{i,j}=1$?
A) $\frac{1}{j-i}$
A) $\frac{2}{j-i+1}$
A) $\frac{2}{n}$
A) $\frac{2}{n^2}$
### Putting Everything together
We have
$$
R=\sum_{i