Книга: A Common-Sense Guide to Data Structures and Algorithms in Python, Volume 1
Назад: Selection Sort in Action
Дальше: Ignoring Constants

The Efficiency of Selection Sort

Selection Sort contains two types of steps: comparisons and swaps. We compare each value with the lowest number we’ve encountered in each pass-through, and we swap the lowest number into its correct position.

Looking back at our example array that contains five elements, we had to make a total of 10 comparisons. Let’s break it down in the following table:

Pass-Through #

# of Comparisons

1

4 comparisons

2

3 comparisons

3

2 comparisons

4

1 comparison

That’s a grand total of 4 + 3 + 2 + 1 = 10 comparisons.

To put it in a way that works for arrays of all sizes, we’d say that for N elements, we make

(N - 1) + (N - 2) + (N - 3) … + 1 comparisons.

As for swaps, though, we only need to make a maximum of one swap per pass-through. This is because in each pass-through, we make either one or zero swaps, depending on whether the lowest number of that pass-through is already in the correct position. Contrast this with Bubble Sort, where in a worst-case scenario we have to make a swap for each and every comparison.

Here’s a side-by-side comparison of Bubble Sort and Selection Sort:

N Elements

Max # of Steps in Bubble Sort

Max # of Steps in Selection Sort

5

20

14 (10 comparisons + 4 swaps)

10

90

54 (45 comparisons + 9 swaps)

20

380

209 (190 comparisons + 19 swaps)

40

1560

819 (780 comparisons + 39 swaps)

80

6320

3239 (3160 comparisons + 79 swaps)

From this comparison, it’s clear Selection Sort takes about half the number of steps Bubble Sort does, indicating that Selection Sort is twice as fast.

Назад: Selection Sort in Action
Дальше: Ignoring Constants