Selection Sort in Action

Using the example array [4, 2, 7, 1, 3], our steps would be as follows:

We begin our first passthrough:

We set things up by inspecting the value at index 0. By definition, it’s the lowest value in the array that we’ve encountered so far (as it’s the only value we’ve encountered so far), so we keep track of its index in a variable:


Step #1: We compare the 2 with the lowest value so far (which happens to be 4):


The 2 is even less than the 4, so it becomes the lowest value so far:

Step #2: We compare the next value—the 7—with ...

Get A Common-Sense Guide to Data Structures and Algorithms now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.