Dale - Computer Science Illuminated 316

Dale - Computer Science Illuminated 316 - alphabet The...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
9.4 Sorting 289 proper place, we are shrinking the unsorted part and extending the sorted part. Sorting begins with all of the list items in the unsorted part and ends with all of the list items in the sorted part. There are only two abstract steps: determining when the list is sorted and finding the index of the smallest element. Moving from Figure 9.9(d) to 9.9(e) added the last two items to the shaded part of the list. This is always the case because when the smaller of the last two is determined and put into its proper place, the last one is also in its proper place. Thus, the loop continues as long as current is less than the length of list 1 . How would you find the name that comes first in the alphabet in the unsorted portion if you were doing it by hand? You see (and mentally record) the first one and then scan down the list until you see one that comes before the first one. You remember this smaller one and continue scanning the list looking for a name that comes before this one in the
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: alphabet. The process of remembering the smallest so far until you find a smaller one is repeated until you reach the end of the list. This by-hand algorithm is exactly the one we use here. Only we must remember the index of the smallest because we are going to swap that item with the item in the current position. So in terms of our list, we look for the smallest in the unsorted portion, which runs from current through length – 1 . Find the index of the smallest Set indexOfSmallest to current For index going from current + 1 to length ± 1 If (list[index].compareTo(list[indexOfSmallest]) < 0) Set indexOfSmallest to index No sorted yet current < length ± 1 Selection Sort Set current to the index of first item in the list While ( not sorted yet ) Find the index of the smallest unsorted item Swap the current item with the smallest unsorted one Incrementing current to shrink unsorted part...
View Full Document

This note was uploaded on 01/13/2011 for the course CSE 1550 taught by Professor Marianakant during the Fall '10 term at York University.

Ask a homework question - tutors are online