12.07.2015 Views

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Sec. 7.2 Three Θ(n 2 ) Sorting <strong>Algorithm</strong>s 241Determining Bubble Sort’s number of comparisons is easy. Regardless of thearrangement of the values in the array, the number of comparisons made by theinner for loop is always i, leading <strong>to</strong> a <strong>to</strong>tal cost ofn∑i = Θ(n 2 ).i=1Bubble Sort’s running time is roughly the same in the best, average, <strong>and</strong> worstcases.The number of swaps required depends on how often a value is less than theone immediately preceding it in the array. We can expect this <strong>to</strong> occur for abouthalf the comparisons in the average case, leading <strong>to</strong> Θ(n 2 ) for the expected numberof swaps. The actual number of swaps performed by Bubble Sort will be identical<strong>to</strong> that performed by Insertion Sort.7.2.3 Selection SortConsider again the problem of sorting a pile of phone bills for the past year. Anotherintuitive approach might be <strong>to</strong> look through the pile until you find the bill forJanuary, <strong>and</strong> pull that out. Then look through the remaining pile until you find thebill for February, <strong>and</strong> add that behind January. Proceed through the ever-shrinkingpile of bills <strong>to</strong> select the next one in order until you are done. This is the inspirationfor our last Θ(n 2 ) sort, called Selection Sort. The ith pass of Selection Sort “selects”the ith smallest key in the array, placing that record in<strong>to</strong> position i. In otherwords, Selection Sort first finds the smallest key in an unsorted list, then the secondsmallest, <strong>and</strong> so on. Its unique feature is that there are few record swaps. To findthe next smallest key value requires searching through the entire unsorted portionof the array, but only one swap is required <strong>to</strong> put the record in place. Thus, the <strong>to</strong>talnumber of swaps required will be n − 1 (we get the last record in place “for free”).Figure 7.3 illustrates Selection Sort. Below is a Java implementation.static

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!