Книга: A Common-Sense Guide to Data Structures and Algorithms in Python, Volume 1
Назад: Chapter 6: Optimizing for Optimistic Scenarios
Дальше: Insertion Sort in Action

Insertion Sort

We’ve previously encountered two different sorting algorithms: Bubble Sort and Selection Sort. Both have efficiencies of O(N2), but Selection Sort is actually twice as fast. Now you’ll learn about a third sorting algorithm called Insertion Sort that will reveal the power of analyzing scenarios beyond the worst case.

Insertion Sort consists of the following steps:

  1. In the first pass-through, we temporarily remove the value at index 1 (the second cell) and store it in a temporary variable. This will leave a gap at that index, since it contains no value:

    /books/45079/OEBPS/optimizing_for_optimistic_scenarios/insertion_sort_1.png
    /books/45079/OEBPS/optimizing_for_optimistic_scenarios/insertion_sort_2.png

    In subsequent pass-throughs, we remove the values at the subsequent indexes.

  2. We then begin a shifting phase, where we take each value to the left of the gap and compare it to the value in the temporary variable:

    /books/45079/OEBPS/optimizing_for_optimistic_scenarios/insertion_sort_3.png

    If the value to the left of the gap is greater than the temporary variable, we shift that value to the right:

    /books/45079/OEBPS/optimizing_for_optimistic_scenarios/insertion_sort_4.png

    As we shift values to the right, inherently the gap moves leftward. As soon as we encounter a value that is lower than the temporarily removed value, or we reach the left end of the array, this shifting phase is over.

  3. We then insert the temporarily removed value into the current gap:

    /books/45079/OEBPS/optimizing_for_optimistic_scenarios/insertion_sort_5.png
  4. Steps 1 through 3 represent a single pass-through. We repeat these pass-throughs until the pass-through begins at the final index of the array. By then, the array will have been fully sorted.

Назад: Chapter 6: Optimizing for Optimistic Scenarios
Дальше: Insertion Sort in Action