Intro to

Algorithms:
Sorting

[CREDITS HERE]

[preface stuff]

  • Agenda?
  • Class format?
  • FAQs?

Evaluating Different Sorting Algorithms

Evaluating Sorting Algorithms:

Complexity

Time Complexity

Space Complexity

How much memory is used?

How many comparisons are made?

How many swaps are made?

...with respect to input size

...and assuming worst case scenarios

Evaluating Sorting Algorithms:

Stability

A sorting algorithm is "stable"

if it preserves the order of

equal items.

Evaluating Sorting Algorithms:

Stability (example)

Prompt: I want bikes sorted by price (ascending). Given equal prices, I want lighter option to be first.

The list is already sorted by weight (ascending). I just need to sort it by price. But an unstable sort based on price could "unsort" weights.

Bike A $600 20 lbs.
Bike B $500 30 lbs.
Bike C $500 35 lbs.

Evaluating Sorting Algorithms:

Adaptability

A sorting algorithm is "adaptive"
if it becomes more efficient

(i.e., if its complexity is reduced)

when the input is

already nearly sorted.

Insertion Sort

Exercise Time!

O(n^2)
O(n2)O(n^2)
O(n^2)
O(n2)O(n^2)
O(1)
O(1)O(1)

Space

Comparisons

Swaps

Insertion Sort

Complexity

Characteristics

Stable:

Adaptive:

O(n)
O(n)O(n)

Insertion Sort

Use Cases

Insertion Sort

Text

Selection Sort

Exercise Time!

O(n^2)
O(n2)O(n^2)
O(1)
O(1)O(1)

Space

Comparisons

Swaps

Selection Sort

Complexity

O(n)
O(n)O(n)

Characteristics

Stable:

Adaptive:

Selection Sort

Use Cases

Selection Sort

Text

Bubble Sort

Exercise Time!

O(n^2)
O(n2)O(n^2)
O(1)
O(1)O(1)

Space

Comparisons

Swaps

Bubble Sort

Complexity

O(n^2)
O(n2)O(n^2)

Characteristics

Stable:

Adaptive:

Bubble Sort

Use Cases

Bubble Sort

Text

Merge Sort

Exercise Time!

O(n*log(n))
O(nlog(n))O(n*log(n))
O(n)
O(n)O(n)

Space

Comparisons

Swaps

Merge Sort

Complexity

arrays

linked lists

O(log(n))
O(log(n))O(log(n))

Characteristics

Stable:

Adaptive:

Merge Sort

Use Cases

Merge Sort

Text

Quick Sort

Exercise Time!

O(n^2)
O(n2)O(n^2)
O(n)
O(n)O(n)

Space

Comparisons

Swaps*

Quick Sort

Complexity

O(n^2)
O(n2)O(n^2)

*Note: Complexity of swapping is implementation-specific

(there are multiple solutions)

Characteristics

Stable:

Adaptive:

Quick Sort

Use Cases

Quick Sort

Text

Recap

  • Complexity
  • Stability
  • Adaptability
  • Divide & Conquer

Recap

Concepts

Recap

Resources & References

Made with Slides.com