Iteration

Quick Sort

Sorting

Here's how QuickSort works.

First Few Test Cases:

0. Problem

We want to make a function called QuickSort to sort the array and return it.

1. Recursion

QuickSort takes a random value in the array and moves everything less than it to its left, and everything greater than it to its right. We can do this in O(n)O(n). This is called "partitioning" the array. Below we randomly pick the number 5\tt 5 to partition the array.

The array isn't sorted after partitioning, but now the 5\tt 5 is in the right place, and everything to the left belongs on the left, and same for the right. To sort the whole array, we can just repeat the process on the left and right sides.

2. Base case

The recursion should stop when the two pointers cross.

3. Code

Time Complexity O(nlogn)O(n \log n) average. It's O(n2)O(n^2) worst-case because you might get very unlucky with the values you pick in your partition, doing an O(n)O(n) operation each time (consider always partitioning the smallest element).

Space Complexity O(n)O(n). Everything is in-place, but the Call Stack gets somewhere between logn\log n to nn calls deep. Even if you converted to iterative you'd need a stack that grows this big.

Partition Implementation

Here's how you implement partition, also called the "Dutch National Flag problem".

Partition would be easy if we used extra memory, but the hard part is doing it in-place without extra memory. The trick is to start a pointer c on the left, and walk left to right, gradually partitioning the array as you walk.

For example, you start like this:

As you walk, you swap elements from the opposite side of the array if needed.

The value you're partitioning might show up multiple times, so you have to keep track of the left and right locations of the value as you walk, which we'll call pL and pR. You can do this by growing pL and pR from the left and right sides of the array as you walk. You just need to make sure everything from 0...pL is less than the value, everything between pL and c is equal to the value, and everything on the right from pR and on is greater than the value.

The stopping point is when c and pR cross.

Here's the code for partition:

Here's the full code:

Unimportant details:

Mark as Completed:
Submits:
quickSort
Test your code to get an output here!
quickSort(
)
Test your code to get an output here!