1 of 146

Insertion Sort and Quicksort

1

Lecture 30 (Sorting 2)

CS61B, Fall 2024 @ UC Berkeley

Slides credit: Josh Hug

Final exam review session:

Friday, November 8, 11:00 AM - 1:30PM

2nd floor Soda Labs (rooms 273, 275, and 277)

2 of 146

Naive Insertion Sort

Lecture 30, CS61B, Fall 2024

Insertion Sort

  • Naive Insertion Sort
  • In-Place Insertion Sort
  • Insertion Sort Runtime

Miscellaneous Sorts

Quicksort

  • Quicksort Backstory,�Partitioning
  • Quicksort

3 of 146

Insertion Sort

General strategy:

  • Starting with an empty output sequence.
  • Add each item from input, inserting into output at right point.

Naive approach, build entirely new output: Demo (Link)

32

15

2

17

19

26

41

17

17

Input:

Output:

4 of 146

Insertion Sort

General strategy:

  • Starting with an empty output sequence.
  • Add each item from input, inserting into output at right point.

Naive approach, build entirely new output:

32

15

2

17

19

26

41

17

17

Input:

Output:

5 of 146

Insertion Sort

General strategy:

  • Starting with an empty output sequence.
  • Add each item from input, inserting into output at right point.

Naive approach, build entirely new output:

32

15

2

17

19

26

41

17

17

32

Input:

Output:

6 of 146

Insertion Sort

General strategy:

  • Starting with an empty output sequence.
  • Add each item from input, inserting into output at right point.

Naive approach, build entirely new output:

32

15

2

17

19

26

41

17

17

32

15

Input:

Output:

7 of 146

Insertion Sort

General strategy:

  • Starting with an empty output sequence.
  • Add each item from input, inserting into output at right point.

Naive approach, build entirely new output:

32

15

2

17

19

26

41

17

17

32

15

2

Input:

Output:

8 of 146

Insertion Sort

General strategy:

  • Starting with an empty output sequence.
  • Add each item from input, inserting into output at right point.

Naive approach, build entirely new output:

32

15

2

17

19

26

41

17

17

32

15

2

17

Input:

Output:

9 of 146

Insertion Sort

General strategy:

  • Starting with an empty output sequence.
  • Add each item from input, inserting into output at right point.

Naive approach, build entirely new output:

32

15

2

17

19

26

41

17

17

32

15

2

17

19

Input:

Output:

10 of 146

Insertion Sort

General strategy:

  • Starting with an empty output sequence.
  • Add each item from input, inserting into output at right point.

Naive approach, build entirely new output:

32

15

2

17

19

26

41

17

17

32

15

2

17

19

26

Input:

Output:

11 of 146

Insertion Sort

General strategy:

  • Starting with an empty output sequence.
  • Add each item from input, inserting into output at right point.

Naive approach, build entirely new output:

32

15

2

17

19

26

41

17

17

32

15

2

17

19

26

41

Input:

Output:

12 of 146

Insertion Sort

General strategy:

  • Starting with an empty output sequence.
  • Add each item from input, inserting into output at right point.

Naive approach, build entirely new output:

32

15

2

17

19

26

41

17

17

32

15

2

17

19

26

41

17

Input:

Output:

13 of 146

Insertion Sort

General strategy:

  • Starting with an empty output sequence.
  • Add each item from input, inserting into output at right point.

Naive approach, build entirely new output:

32

15

2

17

19

26

41

17

17

32

15

2

17

19

26

41

17

17

Input:

Output:

14 of 146

In-Place Insertion Sort

Lecture 30, CS61B, Fall 2024

Insertion Sort

  • Naive Insertion Sort
  • In-Place Insertion Sort
  • Insertion Sort Runtime

Miscellaneous Sorts

Quicksort

  • Quicksort Backstory,�Partitioning
  • Quicksort

15 of 146

Insertion Sort

General strategy:

  • Starting with an empty output sequence.
  • Add each item from input, inserting into output at right point.

For naive approach, if output sequence contains k items, worst cost to insert a single item is k.

  • Might need to move everything over.

More efficient method:

  • Do everything in place using swapping.

16 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

32

15

2

17

19

26

41

17

17

In example above: Use j pointer to track current spot of traveling item.

Input:

17 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

32

15

2

17

19

26

41

17

17

i

j

In example above: Use j pointer to track current spot of traveling item.

Input:

18 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

32

15

2

17

19

26

41

17

17

i

j

sorted

unexamined

In example above: Use j pointer to track current spot of traveling item.

Input:

19 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

32

15

2

17

19

26

41

17

17

i

j

sorted

In example above: Use j pointer to track current spot of traveling item.

unexamined

Input:

20 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

15

32

2

17

19

26

41

17

17

i

j

In example above: Use j pointer to track current spot of traveling item.

unexamined

Input:

21 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

15

32

2

17

19

26

41

17

17

i

j

sorted

In example above: Use j pointer to track current spot of traveling item.

unexamined

Input:

22 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

15

32

2

17

19

26

41

17

17

i

j

sorted

In example above: Use j pointer to track current spot of traveling item.

unexamined

Input:

23 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

15

2

32

17

19

26

41

17

17

i

j

Note: We’ve temporarily broken our invariant that the items up through item i should be sorted!

In example above: Use j pointer to track current spot of traveling item.

unexamined

Input:

24 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

2

15

32

17

19

26

41

17

17

i

j

Once the traveller settles, the invariant is restored.

In example above: Use j pointer to track current spot of traveling item.

unexamined

Input:

25 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

2

15

32

17

19

26

41

17

17

i

j

sorted

In example above: Use j pointer to track current spot of traveling item.

unexamined

Input:

26 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

2

15

32

17

19

26

41

17

17

i

j

sorted

In example above: Use j pointer to track current spot of traveling item.

unexamined

Input:

27 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

2

15

17

32

19

26

41

17

17

i

j

In example above: Use j pointer to track current spot of traveling item.

unexamined

Input:

28 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

2

15

17

32

19

26

41

17

17

i

j

sorted

In example above: Use j pointer to track current spot of traveling item.

unexamined

Input:

29 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

2

15

17

32

19

26

41

17

17

j

sorted

i

In example above: Use j pointer to track current spot of traveling item.

unexamined

Input:

30 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

2

15

17

19

32

26

41

17

17

i

j

In example above: Use j pointer to track current spot of traveling item.

unexamined

Input:

31 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

2

15

17

19

32

26

41

17

17

i

j

sorted

In example above: Use j pointer to track current spot of traveling item.

unexamined

Input:

32 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

2

15

17

19

32

26

41

17

17

i

j

sorted

In example above: Use j pointer to track current spot of traveling item.

unexamined

Input:

33 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

2

15

17

19

26

32

41

17

17

i

j

In example above: Use j pointer to track current spot of traveling item.

unexamined

Input:

34 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

2

15

17

19

26

32

41

17

17

i

j

sorted

In example above: Use j pointer to track current spot of traveling item.

unexamined

Input:

35 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

2

15

17

19

26

32

41

17

17

i

j

sorted

In example above: Use j pointer to track current spot of traveling item.

unexamined

Input:

36 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

2

15

17

19

26

32

41

17

17

i

j

sorted

In example above: Use j pointer to track current spot of traveling item.

unexamined

Input:

37 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

2

15

17

19

26

32

41

17

17

i

j

sorted

In example above: Use j pointer to track current spot of traveling item.

unexamined

Input:

38 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

2

15

17

19

26

32

17

41

17

i

j

In example above: Use j pointer to track current spot of traveling item.

unexamined

Input:

39 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

2

15

17

19

26

17

32

41

17

i

j

In example above: Use j pointer to track current spot of traveling item.

unexamined

Input:

40 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

2

15

17

19

17

26

32

41

17

i

j

In example above: Use j pointer to track current spot of traveling item.

unexamined

Input:

41 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

2

15

17

17

19

26

32

41

17

i

j

In example above: Use j pointer to track current spot of traveling item.

unexamined

Input:

42 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

2

15

17

17

19

26

32

41

17

i

j

sorted

In example above: Use j pointer to track current spot of traveling item.

unexamined

Input:

43 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

2

15

17

17

19

26

32

41

17

i

j

sorted

In example above: Use j pointer to track current spot of traveling item.

unexamined

Input:

44 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

2

15

17

17

19

26

32

17

41

i

j

In example above: Use j pointer to track current spot of traveling item.

Input:

45 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

2

15

17

17

19

26

17

32

41

i

j

In example above: Use j pointer to track current spot of traveling item.

Input:

46 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

2

15

17

17

19

17

26

32

41

i

j

In example above: Use j pointer to track current spot of traveling item.

Input:

47 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

2

15

17

17

17

19

26

32

41

i

j

In example above: Use j pointer to track current spot of traveling item.

Input:

48 of 146

In-place Insertion Sort

General strategy:

  • Repeat for i = 0 to N - 1:
    • Designate item i as the traveling item.
    • Swap item backwards until traveller is in the right place among all previously examined items.

2

15

17

17

17

19

26

32

41

Input:

i

j

In example above: Use j pointer to track current spot of traveling item.

sorted

49 of 146

Insertion Sort Runtime

Lecture 30, CS61B, Fall 2024

Insertion Sort

  • Naive Insertion Sort
  • In-Place Insertion Sort
  • Insertion Sort Runtime

Miscellaneous Sorts

Quicksort

  • Quicksort Backstory,�Partitioning
  • Quicksort

50 of 146

In-place Insertion Sort

Two more examples.

7 swaps:

36 swaps:

P O T A T O

P O T A T O (0 swaps)

O P T A T O (1 swap )

O P T A T O (0 swaps)

A O P T T O (3 swaps)

A O P T T O (0 swaps)

A O O P T T (3 swaps)

S O R T E X A M P L E

S O R T E X A M P L E (0 swaps)

O S R T E X A M P L E (1 swap )

O R S T E X A M P L E (1 swap )

O R S T E X A M P L E (0 swaps)

E O R S T X A M P L E (4 swaps)

E O R S T X A M P L E (0 swaps)

A E O R S T X M P L E (6 swaps)

A E M O R S T X P L E (5 swaps)

A E M O P R S T X L E (4 swaps)

A E L M O P R S T X E (7 swaps)

A E E L M O P R S T X (8 swaps)

Purple: Element that we’re moving left (with swaps).

Black: Elements that got swapped with purple.

Grey: Not considered this iteration.

51 of 146

Insertion Sort Runtime: yellkey.com/TODO

What is the runtime of insertion sort?

  1. Ω(1), O(N)
  2. Ω(N), O(N)
  3. Ω(1), O(N2)
  4. Ω(N), O(N2)
  5. Ω(N2), O(N2)

36 swaps:

52 of 146

Insertion Sort Runtime

What is the runtime of insertion sort?

  • Ω(1), O(N)
  • Ω(N), O(N)
  • Ω(1), O(N2)
  • Ω(N), O(N2)
  • Ω(N2), O(N2)

You may recall Ω is not “best case”.

So technnnniically you could also say � Ω(1)

36 swaps:

53 of 146

Picking the Best Sort: yellkey.com/TODO

Suppose we do the following:

  • Read 1,000,000 integers from a file into an array of length 1,000,000.
  • Mergesort these integers.
  • Select one integer randomly and change it.
  • Sort using algorithm X of your choice.

Which sorting algorithm would be the fastest choice for X?

  1. Selection Sort: O(N2)
  2. Heapsort: O(N Log N)
  3. Mergesort: O(N Log N)
  4. Insertion Sort: O(N2)

54 of 146

Recall: Inversions

An inversion is a pair of elements that are out of order with respect to <.

Another way to state the goal of sorting:

  • Given a sequence of elements with Z inversions.
  • Perform a sequence of operations that reduces inversions to 0.

(9 choose 2) = 45 inversions at most

2

15

17

19

26

17

32

41

17

55 of 146

Recall: Inversions

An inversion is a pair of elements that are out of order with respect to <.

Another way to state the goal of sorting:

  • Given a sequence of elements with Z inversions.
  • Perform a sequence of operations that reduces inversions to 0.

19-17

(out of 45 inversions)

2

15

17

19

26

17

32

41

17

56 of 146

Recall: Inversions

An inversion is a pair of elements that are out of order with respect to <.

Another way to state the goal of sorting:

  • Given a sequence of elements with Z inversions.
  • Perform a sequence of operations that reduces inversions to 0.

19-17, 19-17

(out of 45 inversions)

2

15

17

19

26

17

32

41

17

57 of 146

Recall: Inversions

An inversion is a pair of elements that are out of order with respect to <.

Another way to state the goal of sorting:

  • Given a sequence of elements with Z inversions.
  • Perform a sequence of operations that reduces inversions to 0.

19-17, 19-17, 26-17

(out of 45 inversions)

2

15

17

19

26

17

32

41

17

58 of 146

Recall: Inversions

An inversion is a pair of elements that are out of order with respect to <.

Another way to state the goal of sorting:

  • Given a sequence of elements with Z inversions.
  • Perform a sequence of operations that reduces inversions to 0.

19-17, 19-17, 26-17, 26-17

(out of 45 inversions)

2

15

17

19

26

17

32

41

17

59 of 146

Recall: Inversions

An inversion is a pair of elements that are out of order with respect to <.

Another way to state the goal of sorting:

  • Given a sequence of elements with Z inversions.
  • Perform a sequence of operations that reduces inversions to 0.

19-17, 19-17, 26-17, 26-17

32-17

(out of 45 inversions)

2

15

17

19

26

17

32

41

17

60 of 146

Recall: Inversions

An inversion is a pair of elements that are out of order with respect to <.

Another way to state the goal of sorting:

  • Given a sequence of elements with Z inversions.
  • Perform a sequence of operations that reduces inversions to 0.

19-17, 19-17, 26-17, 26-17

32-17, 41-17 = 6 total inversions

(out of 45 inversions)

2

15

17

19

26

17

32

41

17

61 of 146

Observation: Each swap in Insertion Sort reduces the number of inversions by 1

Inversions between red items don't change (because they don't move)

Inversions between a red and blue item don't change (their relative position in the array stays the same)

We fix one inversion within the blue items

So total number of inversions decrease by 1 every swap

2

15

17

19

26

17

32

41

17

i

j

2

15

17

19

17

26

32

41

17

i

j

62 of 146

Observation: Insertion Sort on Almost Sorted Arrays

For arrays that are almost sorted, insertion sort does very little work.

  • Left array: 5 inversions, so only 5 swaps.
  • Right array: 3 inversion, so only 3 swaps.

63 of 146

Picking the Best Sort (Poll Everywhere)

Suppose we do the following:

  • Read 1,000,000 integers from a file into an array of length 1,000,000.
  • Mergesort these integers.
  • Select one integer randomly and change it.
  • Sort using algorithm X of your choice.
  • In the worst case, we have 999,999 inversions: Θ(N) inversions.

Which sorting algorithm would be the fastest choice for X? Worst case run-times:

  1. Selection Sort: Θ(N2)
  2. Heapsort: Θ(N log N)
  3. Mergesort: Θ(N log N)
  4. Insertion Sort: Θ(N)

64 of 146

Insertion Sort Sweet Spots

On arrays with a small number of inversions, insertion sort is extremely fast.

  • One exchange per inversion (and number of comparisons is similar). Runtime is Θ(N + K) where K is number of inversions.
  • K is on average Θ(N2) in random lists, but…
  • Define an almost sorted array as one in which number of inversions ≤ cN for some c. Insertion sort is excellent on these arrays.

Less obvious: For small arrays (N < 15 or so), insertion sort is fastest.

  • More of an empirical fact than a theoretical one.
  • Theoretical analysis beyond scope of the course.
  • Rough idea: Divide and conquer algorithms like heapsort / mergesort spend too much time dividing, but insertion sort goes straight to the conquest.
  • The Java implementation of Mergesort does this (Link).

65 of 146

Sorts So Far

Best Case Runtime

Worst Case Runtime

Space

Demo

Notes

Θ(N2)

Θ(N2)

Θ(1)

Heapsort

(in place)

Θ(N)*

Θ(N log N)

Θ(1)

Bad cache (61C) performance.

Θ(N log N)

Θ(N log N)

Θ(N)

Fastest of these.

Insertion Sort (in place)

Θ(N)

Θ(N2)

Θ(1)

Best for small N or almost sorted.

See this link for bonus slides on Shell's Sort, an optimization of insertion sort.

66 of 146

Miscellaneous Sorts

Lecture 30, CS61B, Fall 2024

Insertion Sort

  • Naive Insertion Sort
  • In-Place Insertion Sort
  • Insertion Sort Runtime

Miscellaneous Sorts

Quicksort

  • Quicksort Backstory, Partitioning
  • Quicksort

67 of 146

A lightning round of other sorting algorithms

There are many sorting algorithms. Not all of them are actually useful, but they still get referenced every now and then.

We haven't yet covered the fastest sorting algorithms. But before we do that, let's go over a few other sorting algorithms.

68 of 146

Adaptive Sorting Algorithms

On arrays with a small number of inversions, insertion sort is extremely fast.

  • One exchange per inversion (and number of comparisons is similar). Runtime is Θ(N + K) where K is number of inversions.
  • This is known as an adaptive sorting algorithm, since it takes advantage of existing order

More generally, we can think of sorting algorithms that behave like this:

  1. Find a pair of adjacent elements in the wrong order (if you can't find one, the list is sorted)
  2. Swap the two elements
  3. Repeat steps 1 and 2 until the list is sorted

Step 2 fixes one inversion each time, so we get Θ(K) time from that step

Step 1 in insertion sort looks at and solves the inversions of one item at a time, and takes Θ(N+K) in total (since we check N+K total pairs for inversions).

69 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

32

15

2

17

19

26

41

17

17

Input:

70 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

32

15

2

17

19

26

41

17

17

Input:

71 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

15

32

2

17

19

26

41

17

17

Input:

72 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

15

2

32

17

19

26

41

17

17

Input:

73 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

15

2

17

32

19

26

41

17

17

Input:

74 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

15

2

17

19

32

26

41

17

17

Input:

75 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

15

2

17

19

26

32

41

17

17

Input:

76 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

15

2

17

19

26

32

41

17

17

Input:

77 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

15

2

17

19

26

32

17

41

17

Input:

78 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

15

2

17

19

26

32

17

17

41

Input:

79 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

2

15

17

19

26

32

17

17

41

Input:

80 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

2

15

17

19

26

32

17

17

41

Input:

81 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

2

15

17

19

26

32

17

17

41

Input:

82 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

2

15

17

19

26

32

17

17

41

Input:

83 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

2

15

17

19

26

32

17

17

41

Input:

84 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

2

15

17

19

26

17

32

17

41

Input:

85 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

2

15

17

19

26

17

17

32

41

Input:

86 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

2

15

17

19

26

17

17

32

41

Input:

87 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

2

15

17

19

26

17

17

32

41

Input:

88 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

2

15

17

19

26

17

17

32

41

Input:

89 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

2

15

17

19

26

17

17

32

41

Input:

90 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

2

15

17

19

26

17

17

32

41

Input:

91 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

2

15

17

19

17

26

17

32

41

Input:

92 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

2

15

17

19

17

17

26

32

41

Input:

93 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

2

15

17

19

17

17

26

32

41

Input:

94 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

2

15

17

19

17

17

26

32

41

Input:

95 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

2

15

17

19

17

17

26

32

41

Input:

96 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

2

15

17

19

17

17

26

32

41

Input:

97 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

2

15

17

19

17

17

26

32

41

Input:

98 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

2

15

17

17

19

17

26

32

41

Input:

99 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

(At this point, the list is sorted, but we run through the list one more time to confirm that)

2

15

17

17

17

19

26

32

41

Input:

100 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

(At this point, the list is sorted, but we run through the list one more time to confirm that)

2

15

17

17

17

19

26

32

41

Input:

101 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

(At this point, the list is sorted, but we run through the list one more time to confirm that)

2

15

17

17

17

19

26

32

41

Input:

102 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

(At this point, the list is sorted, but we run through the list one more time to confirm that)

2

15

17

17

17

19

26

32

41

Input:

103 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

(At this point, the list is sorted, but we run through the list one more time to confirm that)

2

15

17

17

17

19

26

32

41

Input:

104 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

(At this point, the list is sorted, but we run through the list one more time to confirm that)

2

15

17

17

17

19

26

32

41

Input:

105 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

(At this point, the list is sorted, but we run through the list one more time to confirm that)

2

15

17

17

17

19

26

32

41

Input:

106 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

(At this point, the list is sorted, but we run through the list one more time to confirm that)

2

15

17

17

17

19

26

32

41

Input:

107 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

(At this point, the list is sorted, but we run through the list one more time to confirm that)

2

15

17

17

17

19

26

32

41

Input:

108 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

(At this point, the list is sorted, but we run through the list one more time to confirm that)

2

15

17

17

17

19

26

32

41

Input:

109 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

(At this point, the list is sorted, but we run through the list one more time to confirm that)

2

15

17

17

17

19

26

32

41

Input:

110 of 146

Bad sorting algorithm: Bubble sort

Bubble sort:

Iterate through the list and look at each adjacent pair

If the two elements are in a wrong order, swap them

Repeat iterating through list until the array is sorted

2

15

17

17

17

19

26

32

41

Input:

111 of 146

Bad sorting algorithm: Bubble sort

Bubble sort is the same as insertion sort, except it doesn't find inversions as quickly.

Very slow in theory, and slow in practice too (~5x slower than insertion sort)

Items that need to move left are "turtles" that take a long time to move to the right spot.

Other variations of insertion sort:

  • Cocktail shaker sort
    • Bubble sort but iteration order swaps forwards and backwards
    • Fixes the issue of turtles, but still slow
  • Shell sort
    • Instead of comparing adjacent items, compare at longer distances first to fix multiple inversions at once.
    • Depending on the jump lengths, can yield better asymptotic runtime than insertion sort
    • See this link for more info

112 of 146

Shuffling

Let's try solving the "reverse" problem to sorting: Shuffling

Given a list of n elements and a random number generator, return a random permutation (reordering) of the list.

The random number generator receives as input two integers i and j, and returns a random integer between i and j.

Goals:

  • Even distribution (after shuffling, each of the n! permutations are equally likely)
  • Fast runtime (Θ(n) runtime)

1

2

3

4

5

6

7

8

9

Input:

113 of 146

Shuffling

For each number i from 0 to n-1:

  • Pick a random item by selecting an index from i to n-1
  • Swap that item with the item in index i

1

2

3

4

5

6

7

8

9

Input:

114 of 146

Shuffling

For each number i from 0 to n-1:

  • Pick a random item by selecting an index from i to n-1
  • Swap that item with the item in index i

1

2

3

4

5

6

7

8

9

Input:

i

115 of 146

Shuffling

For each number i from 0 to n-1:

  • Pick a random item by selecting an index from i to n-1
  • Swap that item with the item in index i

7

2

3

4

5

6

1

8

9

Input:

i

116 of 146

Shuffling

For each number i from 0 to n-1:

  • Pick a random item by selecting an index from i to n-1
  • Swap that item with the item in index i

7

2

3

4

5

6

1

8

9

Input:

i

117 of 146

Shuffling

For each number i from 0 to n-1:

  • Pick a random item by selecting an index from i to n-1
  • Swap that item with the item in index i

7

9

3

4

5

6

1

8

2

Input:

i

118 of 146

Shuffling

For each number i from 0 to n-1:

  • Pick a random item by selecting an index from i to n-1
  • Swap that item with the item in index i

7

9

3

4

5

6

1

8

2

Input:

i

119 of 146

Shuffling

For each number i from 0 to n-1:

  • Pick a random item by selecting an index from i to n-1
  • Swap that item with the item in index i

7

9

3

4

5

6

1

8

2

Input:

i

120 of 146

Shuffling

For each number i from 0 to n-1:

  • Pick a random item by selecting an index from i to n-1
  • Swap that item with the item in index i

(Remaining Steps omitted)

7

9

3

4

5

6

1

8

2

Input:

i

121 of 146

Shuffling

For each number i from 0 to n-1:

  • Pick a random item by selecting an index from i to n-1
  • Swap that item with the item in index i

7

9

3

1

2

4

6

5

8

Input:

i

122 of 146

Shuffling

For each number i from 0 to n-1:

  • Pick a random item by selecting an index from i to n-1
  • Swap that item with the item in index i

Runtime?

7

9

3

1

2

4

6

5

8

Input:

i

123 of 146

Shuffling

For each number i from 0 to n-1:

  • Pick a random item by selecting an index from i to n-1
  • Swap that item with the item in index i

Runtime? Θ(n) (We do n iterations of constant time each)

Even distribution?

7

9

3

1

2

4

6

5

8

Input:

i

124 of 146

Shuffling

For each number i from 0 to n-1:

  • Pick a random item by selecting an index from i to n-1
  • Swap that item with the item in index i

Runtime? Θ(n)

Even distribution? Perfectly even (Each permutation has exactly one way of being created, with probability 1/n * 1/(n-1) * … * (1/1) = 1/(n!)

7

9

3

1

2

4

6

5

8

Input:

i

125 of 146

Bad sorting algorithm: BOGO sort

BOGO sort:

While list is not sorted: (O(n) time to check if list is sorted)

  • Shuffle the list (Θ(n) time to shuffle)

Let's analyze this quickly:

Best-case runtime:

Worst-case runtime:

Average runtime:

126 of 146

Bad sorting algorithm: BOGO sort

Here's a bad sorting algorithm:

While list is not sorted: (O(n) time to check if list is sorted)

  • Shuffle the list (Θ(n) time to shuffle)

Let's analyze this quickly:

Best-case runtime: Θ(n) (if the list is sorted initially)

Worst-case runtime: Infinite runtime (if we never shuffle it the right way)

Average runtime: Θ(n*n!) (while loop has on average n! iterations before we get the sorted order)

127 of 146

Quicksort Backstory, Partitioning

Lecture 30, CS61B, Fall 2024

Insertion Sort

  • Naive Insertion Sort
  • In-Place Insertion Sort
  • Insertion Sort Runtime

Miscellaneous Sorts

Quicksort

  • Quicksort Backstory, Partitioning
  • Quicksort

128 of 146

Sorts So Far

Best Case Runtime

Worst Case Runtime

Space

Demo

Notes

Θ(N2)

Θ(N2)

Θ(1)

Heapsort

(in place)

Θ(N)*

Θ(N log N)

Θ(1)

Bad cache (61C) performance.

Θ(N log N)

Θ(N log N)

Θ(N)

Fastest of these.

Insertion Sort (in place)

Θ(N)

Θ(N2)

Θ(1)

Best for small N or almost sorted.

129 of 146

Sorting So Far

Core ideas:

  • Selection sort: Find the smallest item and put it at the front.
    • Heapsort variant: Use MaxPQ to find max element and put at the back.
  • Merge sort: Merge two sorted halves into one sorted whole.
  • Insertion sort: Figure out where to insert the current item.

Quicksort:

  • Core idea: Partitioning.
  • Invented by Sir Tony Hoare in 1960, at the time a novice programmer.

130 of 146

Context for Quicksort’s Invention (Source)

1960: Tony Hoare was working on a crude automated translation program for Russian and English. �

  • Binary search for each word.
    • Find “the” in log D time.
    • Find “cat” in log D time...
  • Total time: N log D

...

...

beautiful

красивая

...

...

cat

кошка

...

...

“The cat wore a beautiful hat.”

Dictionary of D english words

N words

“Кошка носил красивая шапка.”

How would you do this?

131 of 146

Context for Quicksort’s Invention (Source)

Limitation at the time:

  • Dictionary stored on long piece of tape, sentence is an array in RAM.
    • Binary search of tape is not log time (requires physical movement!).
  • Better: Sort the sentence and scan dictionary tape once. Takes N log N + D time.
    • But Tony had to figure out how to sort an array (without Google!)...�

1960: Tony Hoare was working on a crude automated translation program for Russian and English.

Algorithm: N binary searches of D length dictionary.

  • Total runtime: N log D
  • ASSUMES log time binary search!

...

...

beautiful

красивая

...

...

cat

кошка

...

...

132 of 146

Partitioning

Main idea: I have a list of small and large items. To sort this:

  • Separate the small items and large items into two separate piles
  • Sort the small items
  • Sort the large items
  • Put the sorted lists together

How to decide what's big and what's small?

  • Pick an item from the list (we'll call this the pivot). Smaller items are small, and bigger items are big

We'll call this a partition; we separate the big items and the small items, and put remaining items in the middle.

133 of 146

Partitioning

A partition of an array, given a pivot x, is a rearrangement of the items so that:

  • All entries to the left of x are <= x.
  • All entries to the right of x are >= x.
  • x moves between the smaller and larger items

3

1

2

4

6

8

7

3

4

1

2

6

7

8

Example of a valid output

Another example of a valid output

6

8

3

1

2

7

4

Input

9

9

9

134 of 146

Core Idea of Tony’s Sort: Partitioning http://yellkey.com/TODO

A partition of an array, given a pivot x, is a rearrangement of the items so that:

  • All entries to the left of x are <= x.
  • All entries to the right of x are >= x.

Which partitions are valid?

5

550

10

4

10

9

330

4

5

9

10

10

330

550

5

9

10

4

10

550

330

5

4

9

10

10

550

330

5

9

10

4

10

550

330

A.

C.

B.

D.

j

j

j

j

135 of 146

The Core Idea of Tony’s Sort: Partitioning

A partition of an array, given a pivot x, is a rearrangement of the items so that:

  • All entries to the left of x are <= x.
  • All entries to the right of x are >= x.

Which partitions are valid?

5

550

10

4

10

9

330

i

4

5

9

10

10

330

550

5

9

10

4

10

550

330

5

4

9

10

10

550

330

5

9

10

4

10

550

330

A.

C.

B.

D.

j

j

j

j

Called the ‘pivot’.

136 of 146

Job Interview Style Question (Partitioning)

Given an array of colors where the 0th element is white (and maybe a few more), and the remaining elements are red (less) or blue (greater), rearrange the array so that all red squares are to the left of the white square, the white squares end up together, and all blue squares are to the right. Your algorithm must complete in Θ(N) time (no space restriction).

  • Relative order of red and blues does NOT need to stay the same.

3

1

2

4

6

8

7

3

4

1

2

6

7

8

Example of a valid output

Another example of a valid output

6

8

3

1

2

7

4

Input

6

6

6

137 of 146

Quicksort

Lecture 30, CS61B, Fall 2024

Insertion Sort

  • Naive Insertion Sort
  • In-Place Insertion Sort
  • Insertion Sort Runtime

Miscellaneous Sorts

Quicksort

  • Quicksort Backstory,�Partitioning
  • Quicksort

138 of 146

Partition Sort, a.k.a. Quicksort

Observations:

  • 5 is “in its place.” Exactly where it’d be if the array were sorted.
  • Can sort two halves separately, e.g. through recursive use of partitioning.

5

3

2

1

8

4

6

7

3

2

1

4

7

8

6

5

3

2

1

4

5

7

8

6

5

2

1

3

4

5

6

7

8

5

Q: How would we use this operation for sorting?

139 of 146

Quick Sort

Quick sorting N items:

  • Partition on leftmost item.
  • Quicksort left half.
  • Quicksort right half.

32

15

2

17

19

26

41

17

17

Input:

unsorted

140 of 146

Quick Sort

Quick sorting N items:

  • Partition on leftmost item (32).
  • Quicksort left half.
  • Quicksort right half.

32

15

2

17

19

26

41

17

17

Input:

partition(32)

141 of 146

Quick Sort

Quick sorting N items:

  • Partition on leftmost item (32).
  • Quicksort left half.
  • Quicksort right half.

15

2

17

19

26

17

17

32

41

Input:

<= 32

>= 32

in its place

partition(32)

142 of 146

Quick Sort

Quick sorting N items:

  • Partition on leftmost item (32) (done).
  • Quicksort left half.
  • Quicksort right half.

15

2

17

19

26

17

17

32

Input:

in its place

41

partition(32)

143 of 146

Quick Sort

Quick sorting N items:

  • Partition on leftmost item (32) (done).
  • Quicksort left half (details not shown).
  • Quicksort right half.

partition(32)

partition(15)

partition(2)

partition(17)

partition(19)

partition(17)

partition(17)

partition(26)

x

x

x

x

x

x

x

2

15

17

17

17

19

26

32

41

Input:

in its place

in its place

in its place

in its place

in its place

in its place

in its place

in its place

x

144 of 146

Quick Sort

Quick sorting N items:

  • Partition on leftmost item (32) (done).
  • Quicksort left half (details not shown).
  • Quicksort right half (details not shown).

partition(32)

partition(15)

partition(2)

partition(17)

partition(19)

partition(17)

partition(17)

partition(26)

x

x

x

x

x

x

x

2

15

17

17

17

19

26

32

41

Input:

in its place

in its place

in its place

in its place

in its place

in its place

in its place

in its place

in its place

If you don't fully trust the recursion, see these extra slides for a complete demo.

x

145 of 146

Partition Sort, a.k.a. Quicksort

Quick sorting N items:

  • Partition on leftmost item.
  • Quicksort left half.
  • Quicksort right half.

32

15

2

17

19

26

41

17

17

partition(32)

15

2

17

19

26

17

17

32

41

<= 32

>= 32

in its place

146 of 146

Quicksort

Quicksort was the name chosen by Tony Hoare for partition sort.

  • For most common situations, it is empirically the fastest sort.
    • Tony was lucky that the name was correct.

How fast is Quicksort? Need to count number and difficulty of partition operations.

Theoretical analysis:

  • Partitioning costs Θ(K) time, where Θ(K) is the number of elements being partitioned (as we saw in our earlier “interview question”).
  • The interesting twist: Overall runtime will depend crucially on where pivot ends up.