Skip to contentKEEP THE CRAFTTHE SANCTUARY

Quick Sort

Partition a range around a pivot, finalize that pivot, then sort only the remaining sides. Understand duplicate policy, imbalance and why a deterministic last-pivot Lab does not guarantee expected bounds.

1 practice exercise4 interview problems

Recognize it when A comparison sort may trade stability for partitioning and low extra storage.

Checking your account…

Quick Sort Code Labs

Partition Around a Pivot

Partitioning rearranges one range so values on one side satisfy the pivot relation and values on the other side do not. The pivot reaches a final position for that partition scheme.

Maintain Three Partition Regions

During Lomuto partition, the prefix is less than or equal to pivot, the middle has been inspected and is greater, and the suffix is unseen. Swapping an accepted value grows the first region.

Trace Lomuto Partition

Reference
def partition_trace(values):
    values=values.copy();pivot=values[-1];boundary=0;trace=[]
    for index in range(len(values)-1):
        if values[index]<=pivot:
            values[boundary],values[index]=values[index],values[boundary];trace.append(values.copy());boundary+=1
    values[boundary],values[-1]=values[-1],values[boundary];trace.append(values.copy());return trace
Practice

Implement partition_trace(values). Use the last value as pivot and return array states after each swap, including final pivot placement. values must be nonempty.

Public tests

  • Grow the less-or-equal region

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Lomuto Partition

def partition_trace(values):
    values=values.copy();pivot=values[-1];boundary=0;trace=[]
    for index in range(len(values)-1):
        if values[index]<=pivot:
            values[boundary],values[index]=values[index],values[boundary];trace.append(values.copy());boundary+=1
    values[boundary],values[-1]=values[-1],values[boundary];trace.append(values.copy());return trace

Grow the Accepted Prefix Before Placing the Pivot

Predict the two snapshots returned by the existing Lomuto Lab. Rejected comparisons produce no row; accepted swaps, including a swap with itself, do.

Step Executed statement State Why
Choose pivot values=values.copy();pivot=values[-1];boundary=0;trace=[] pivot=2, boundary=0 The copied input permits rearrangement without changing the caller list.
Reject 4 if values[index]<=pivot: index=0, boundary=0 4 belongs to the greater-than region.
Accept 1 values[boundary],values[index]=values[index],values[boundary];trace.append(values.copy());boundary+=1 values=[1, 4, 3, 2], boundary then 1 The swap extends the at-most-pivot prefix by one item.
Reject 3 if values[index]<=pivot: index=2, boundary=1 The inspected 3 remains on the greater side.
Place pivot values[boundary],values[-1]=values[-1],values[boundary] values=[1, 2, 3, 4] The pivot is now final for this range; neither recursive side should include index 1.
Print Output
print(partition_trace([4, 1, 3, 2])) [[1, 4, 3, 2], [1, 2, 3, 4]]

A sorted result for this small partition does not mean partition generally sorts either side. The second Lab recurses on both sides and exposes the worst-case depth of its deterministic pivot choice.

Recurse Only on Unsettled Sides

After pivot placement, exclude the pivot from both recursive ranges. Base cases of size zero or one prevent repeated boundaries and guarantee termination.

Quick Sort Values

Reference
def quick_sort(values):
    values=values.copy()
    def sort(left,right):
        if left>=right:return
        pivot=values[right];boundary=left
        for index in range(left,right):
            if values[index]<=pivot:values[boundary],values[index]=values[index],values[boundary];boundary+=1
        values[boundary],values[right]=values[right],values[boundary]
        sort(left,boundary-1);sort(boundary+1,right)
    sort(0,len(values)-1);return values
Practice

Implement quick_sort(values). Return a sorted copy using in-place partitioning on the copy.

Public tests

  • Sort both unsettled partitions

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Quick Sort Values

def quick_sort(values):
    values=values.copy()
    def sort(left,right):
        if left>=right:return
        pivot=values[right];boundary=left
        for index in range(left,right):
            if values[index]<=pivot:values[boundary],values[index]=values[index],values[boundary];boundary+=1
        values[boundary],values[right]=values[right],values[boundary]
        sort(left,boundary-1);sort(boundary+1,right)
    sort(0,len(values)-1);return values

Control Worst Case and Stack Depth

Balanced partitions give O(n log n); consistently extreme partitions give O(n squared) and O(n) recursion depth. Random pivots give the expected bound for distinct keys, but do not repair this two-way partition on all-equal input: every pivot still leaves n minus one values on one side. A three-way equal region avoids that duplicate-driven degeneration. To bound recursion depth, recurse on the smaller side and process the larger side iteratively; visiting the smaller side first while still recursively calling both sides does not itself bound the stack.

Explain It in an Interview

Say: “These regions are the partition invariant; each scan step classifies one value, then the pivot is final.” State duplicate policy, input mutation, average and worst-case time, and recursion-space behavior.

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Quicksort with random/order-balanced pivotsO(n log n)O(n^2)The expected random-pivot bound assumes distinct keys or duplicate-aware partitioning. This deterministic two-way <= Lab is quadratic on all-equal inputs even if pivot positions are randomized.

Space

The Lab copies O(n) input storage and uses O(log n) balanced/O(n) worst-case frames.

Assumptions

  • The trace Lab copies the entire array after each swap, adding O(n^2) trace work/space for one partition.
  • To bound recursion by recursing on the smaller side, process the larger side iteratively; merely sorting the smaller side first is insufficient.

Invariants Worth Saying Aloud

  1. Before boundary, values are <= pivot; inspected values after boundary are > pivot.
  2. The uninspected suffix still contains every unclassified item.
  3. After final swap the pivot is excluded from both recursive ranges.

When To Use Or Avoid Quick Sort

Use It When

  • Use partitioning when in-place rearrangement and an explicit pivot invariant are useful.
  • Randomized pivots support an expected bound for distinct keys; use duplicate-aware three-way partitioning when many values can be equal.

Choose Another Tool When

  • Use a stable maintained sort when equal-record input order matters.
  • A last-element pivot is vulnerable to already ordered inputs and repeated equal values.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Including the pivot in its own recursive range

If the pivot reaches right, sort(left, boundary) repeats the whole range.

Prevent it: Exclude its finalized index from the child interval.

Avoid

next_right = boundary

Use instead

next_right = boundary - 1

Dropping equal pivot values

Retaining only one pivot while using strict lower/higher groups deletes duplicate values.

Prevent it: Keep every equal value in a three-way partition, or retain duplicates in the in-place scheme.

Avoid

equal = [pivot]

Use instead

equal = [value for value in values if value == pivot]

Saving a live array instead of a swap snapshot

Appending the same mutable list makes earlier trace entries show later swaps.

Prevent it: Copy only for an intentional trace snapshot; this copying is not free.

Avoid

trace.append(values)

Use instead

trace.append(values.copy())

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.