Selection Sort

In the previous chapter, we explored an algorithm for sorting data known as Bubble Sort, which had an efficiency of O(N2). We’re now going to dig into another sorting algorithm called Selection Sort, and see how it measures up to Bubble Sort.

The steps of Selection Sort are as follows:

  1. We check each cell of the array from left to right to determine which value is least. As we move from cell to cell, we keep in a variable the lowest value we’ve encountered so far. (Really, we keep track of its index, but for the purposes of the following diagrams, we’ll just focus on the actual value.) If we encounter a cell that contains a value that is even less than the one in our variable, we replace it so that the variable now points to the new index. See the following diagram:

    images/chapter6/optimizing_code_big_o-centered-no-text_Part1-4.png
    images/chapter6/optimizing_code_big_o-centered-no-text_Part5.pngimages/chapter6/optimizing_code_big_o-centered-no-text_Part6.png
  2. Once we’ve determined which index contains the lowest value, we swap that index with the value we began the passthrough with. This would be index 0 in the first passthrough, index 1 in the second passthrough, and so on and so forth. In the next diagram, we make the swap of the first passthrough:

  3. Repeat steps 1 and 2 until all the data is sorted.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset