Searching for the Two Smallest Values

This section will explore how to find the index of the two smallest items in an unsorted list using three quite different algorithms. We’ll go through a top-down design using each approach.

To start, suppose we have data showing the number of humpback whales sighted off the coast of British Columbia over the past ten years:

809

834

477

478

307

122

96

102

324

476

The first value, 809, represents the number of sightings ten years ago; the last one, 476, represents the number of sightings last year.

We’ll start with a simpler problem: what is the smallest value during those years? This code tells us just that:

 >>>​​ ​​counts​​ ​​=​​ ​​[809,​​ ​​834,​​ ​​477,​​ ​​478,

Get Practical Programming, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.