# 36.3 MSD Radix Sort

<details>

<summary>Suppose we sort by topmost digit, then middle digit, then rightmost digit. Will we arrive at the correct result?</summary>

No, this will result in sorting the array by right most digit only as we are not saving the topmost and middle digit.

</details>

<figure><img src="https://github.com/Berkeley-CS61B/fa25-gitbook/blob/main/.gitbook/assets/Screen%20Shot%202023-04-15%20at%202.55.34%20AM.png" alt=""><figcaption><p>MSD Radix Sort (correct edition)</p></figcaption></figure>

Notice first we sorted by leftmost digit. Then we grouped the data by the leftmost digit, so one group would start with a's, then the next group would start with b's, and so on and so forth. Then within our subgroups we would order by middle digit, and create newer subgroups. And finally we would break this up into further subgroups until we have all individual subproblems. This final result would be sorted.

### Runtimes

Best Case.

* We finish in one counting sort pass, looking only at the top digit: $$\Theta(N+R)$$

Worst Case.

* We have to look at every character, degenerating to LSD sort: $$\Theta(WN+WR)$$

### Summary of Runtimes

<figure><img src="https://github.com/Berkeley-CS61B/fa25-gitbook/blob/main/.gitbook/assets/Screen%20Shot%202023-04-15%20at%202.58.27%20AM.png" alt=""><figcaption></figcaption></figure>
