Skip to Content
A Common-Sense Guide to Data Structures and Algorithms
book

A Common-Sense Guide to Data Structures and Algorithms

by Jay Wengrow
August 2017
Intermediate to advanced
222 pages
5h 3m
English
Pragmatic Bookshelf
Content preview from A Common-Sense Guide to Data Structures and Algorithms

The Efficiency of Selection Sort

Selection Sort contains two types of steps: comparisons and swaps. That is, we compare each element with the lowest number we’ve encountered in each passthrough, and we swap the lowest number into its correct position.

Looking back at our example of an array containing five elements, we had to make a total of ten comparisons. Let’s break it down.

Passthrough #

# of comparisons

1

4 comparisons

2

3 comparisons

3

2 comparisons

4

1 comparison

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

To put it more generally, we’d say that for N elements, we make

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

As for swaps, however, we only need to make a maximum of one swap per passthrough. This is because in each passthrough, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

A Common-Sense Guide to Data Structures and Algorithms, Second Edition, 2nd Edition

A Common-Sense Guide to Data Structures and Algorithms, Second Edition, 2nd Edition

Jay Wengrow

Publisher Resources

ISBN: 9781680502794Errata Page