Return to the Lecture Notes Index

15-100 Lecture 21 (Monday, March 17, 2008)

Insertion Sort

Last class we implemented an insert-in-order method. Each time we used it, it added the new item into the list in the "right" place to keep the lsit in sorted order. Using this technique, we can sort a list.

We begin with an unsorted list. Then, we create a new array. We insert each item from the old list into the new list, one at a time, using our insert-in-order technique. Once we're done, we can move the list reference from the unsorted array to the srted array -- leaving the unsorted one for the garbage collector.

But, this requires that we have at least twice as much memory as we really need, at least temporarily. During the sort, we keep both the unsorted and sort-in-progress arrays in memory at the same time.

What we are going to do next is to createa an "in place" sort based on the same technique. It will sort an array of items "in place", without a temporary array. It works as follows.

We begin by viewing the list as a list of one item, the item at the 0th position. A list of one item is necessarily sorted as nothing can be out of order. Then, we consider the 1st item. If it is in the right place -- great! If not, we move it into a temporary variable, creating a "hole". At this point, thinks work just as they did with our insert-in-order. We shift items backward, shifting the hole forward, until we can drop the item from the temporary variable itno the hole. With each iteration, we work from the front of the list to the end of the list, moving the next item into the proper location.

Here's an example:

4 7 9 2 5 8 1 3 6
4 7 9 2 5 8 1 3 6
4 7 9 2 5 8 1 3 6
4 7 9 2 5 8 1 3 6
4 7 9 2 5 8 1 3 6
2 4 7 9 5 8 1 3 6
2 4 7 9 5 8 1 3 6
2 4 5 7 9 8 1 3 6
2 4 5 7 9 8 1 3 6
2 4 5 7 8 9 1 3 6
2 4 5 7 8 9 1 3 6
1 2 4 5 7 8 9 3 6
1 2 4 5 7 8 9 3 6
1 2 3 4 5 7 8 9 6
1 2 3 4 5 7 8 9 6
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9

Insertion Sort Code

In class, we developed the code below, which implements an insertion sort in the context of a ComparableArrayList similar to last class's SortedArrayList.

 public void insertionSort() {
    // Ensure that we've got enough room
    if (count == list.length) grow();

    // For each item, find its position w/in the sorted items to the left
    for (int insertMe=1; insertMe < count; insertMe++)
    {
      // Save the item so we can use its space to shift back
      Comparable newItem = list[insertMe];

      // Very important that newPosn isn't declared as part of the loop. Why?
      int newPosn; 
      for (newPosn=count; newPosn > 0; newPosn--)
      {
        if (list[newPosn-1] < newItem)
          break; // We've found the right place
        
        // Otherwise, shift and loop back to check again
        list[newPosn] = list[newPosn-1];
      }

      // Put this iterations new item into its place
      list[newPosn] = newItem;
    }
  }