X y 3 y tmp cpsc 223 2009 19 selection sort what

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

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: theArray[j] >= theArray[index]) index = j; // 1 move } // end inner for swap(theArray[index], theArray[i]); // 3 moves } // end outer for } CPSC 223, 2009 18 9 9/23/10 Evaluating Sorting Algorithms Number of comparisons –  How many pairs of items are compared within a pass Number of moves –  How many times do we move list items –  Within a list or to a temporary variable •  We often do “swaps” void swap(int& x, int& y) // here just integers { int tmp = x; How many moves in a swap? x = y; 3 y = tmp; } CPSC 223, 2009 19 Selection Sort What is the best and worst case? –  They are the same for selection sort! What is the cost? –  The outer loop executes n – 1 times (passes) –  Each pass p requires n – p comparisons Σp = 1 .. n – 1 (n – p) = (n – 1) + (n – 2) + … + 1 = n*(n – 1)/2 –  Thus, insertion sort is O(n2)! Check that we would get the same result if we analyzed moves instead of comparisons CPSC 223, 2009 20 10 9/23/10 Comparison of Sorting Algorithms Best Case SelecRon Sort Average Case Worst Case O(n2) O(n2) O(n2) Bubble Sort InserRon Sort Mergesort Quicksort Heapsort Treesort CPSC 223, 2009 21 Bubble Sort The basic idea: –  Compare adjacent items … –  Exchange items if they are out of order –  Repeat for n – 1 passes –  Each pass p requires n – p comparisons Pass 2 Pass 3 IniRal list: 29 10 14 13 (n=4) 10 29 14 13 10 14 13 29 10 13 14 29 10 14 13 29 10 13 14 29 10 14 29 13 10 13 14 29 Pass 1 10 14 13 29 CPSC 223, 2009 22 11 9/23/10 Bubble Sort (based on textbook) void bubbleSort(Entry theArray, int n) { bool sorted = false; for(int i = 1; i...
View Full Document

This document was uploaded on 03/18/2014 for the course CPSC 223 at Gonzaga.

Ask a homework question - tutors are online