Page 307 - Learn to Program - Basic-256
P. 307

Chapter 19: Stacks, Queues, Lists, and Sorting                                  Page 291



                                     Original Array

                     2  7   1  3   5   4  6
                     unsorted                                                  b   5
                                     Start with second element and
                                     insert it where it goes in sorted part
                        7                                           1   2  3       7  4   6
                     a               (shift if needed to make room)
                                                                               a       unsorted
                     2      1  3   5   4  6
                            unsorted                                             c    4

                       c    1        Shift the elements in the sorted part and  1  2  3  5  7  6
                                     insert the next element where it goes
                                                                               b   a      unsorted
                        2   7  3   5   4  6
                     b   a      unsorted                                               b  6

                                     Keep shifting and inserting each element
                            b  3     until you have gone through all of the  1  2  3  4  5  7
                                     unsorted items in the array
                                                                                       a
                     1  2      7   5   4  6
                            a      unsorted                                          Sorted Array

                                                                    1   2  3   4   5  6   7
            Illustration 37: Insertion Sort - Step-by-step




                1       # insertionsort.kbs
                2       # implementing an efficient sort
                3
                4       # The insertion sort loops through the items
                5       # starting at the second element.
                6
                7       # takes current element and inserts it
                8       # in the the correct sorted place in
                9       # the previously sorted elements
                10
                11      # moving from backward from the current
                12      # location and sliding elements with a


                                                           © 2019 James M. Reneau (CC BY-NC-SA 3.0 US)
   302   303   304   305   306   307   308   309   310   311   312