n 1 n i n 1 n 2 1 nn 12 thus in

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: < n && !sorted; i++) { sorted = true; for(int j = 0; j < (n – i); j++) { if(theArray[j] > theArray[j+1]) { swap(theArray[j], theArray[j+1]); sorted = false; } } // end inner for } // end outer for } CPSC 223, 2009 23 Bubble Sort What is the best and worst case? –  Can check if array is sorted before next pass •  If no items require exchanging then don’t proceed –  So the best case is when the list is already sorted •  It takes one pass of n – 1 comparisons … O(n) –  Worst case when the list is sorted from highest to lowest •  Requires n – 1 passes •  Each pass p requires n – p comparisons Σi = 1 .. n – 1 (n – i) = (n – 1) + (n – 2) + … + 1 = n*(n – 1)/2 –  Thus, in the worst case for bubble sort is O(n2)! CPSC 223, 2009 24 12 9/23/10 Comparison of Sorting Algorithms Best Case Average Case Worst Case SelecRon Sort O(n2) O(n2) O(n2) Bubble Sort O(n) O(n2) O(n2) InserRon Sort Mergesort Quicksort Heapsort Treesort CPSC 223, 2009 25 Insertion Sort The basic idea: –  Partition list into sorted and unsorted regions –  Select first item in unsorted region –  Insert item into the right location of sorted region –  Shift larger items one location forward in the list Pass 2 Pass 3 IniRal list: 29 10 14 13 (n=4) 29 10 14 13 10 29 14 13 10 14 29 13 10 29 14 13 10 14 29 13 10 29 14 13 10 14 29 13 10 13 14 29 Pass 1 CPSC 223, 2009 26 13 9/23/10 Insertion Sort (based on textbook) void insertionSort(Entry theArray, int n) { for(int i = 1; i < n; i++) { Entry next = theArray[i]; int j = i; // insertion index while(j > 0 && theArray[j-1] > next) { theArray[j] = theArray[j-1]; // shift j = j – 1; } // end inner for theArray[j] = next; } // end outer for } CPSC 223, 2009 27 Insertion Sort What is the best and worst case? –  Worst case is when inner loop has to shift (n – 1) times •  … which happens when list is in reverse order –  Best case is when list is already in order •  … outer loop executes n – 1 times doing nothing in inner loop What is the worst-case cost? –  The outer loop executes n – 1 times (passes) –  Each pass p requires p comparisons Σp = 1 .. n – 1 p = 1 + 2 + … + (n – 1) = n*(n – 1)/2 –  Each pass p also requires p data-item shifts   Thus, insertion sort is O(n2)! CPSC 223, 2009 28 14 9/23/10 Evaluating Sorting Algorithms An example of why counting comparisons separately from moves is useful … –  A variant of insertion sort is “binary” insertion sort –  Here we find the insert location using a binary search –  Comparisons go from O(n) on each pass to O(log n)! –  The algorithm is still O(n2) … why? •  Many of the algorithms we discuss have variants CPSC 223, 2009 29 15...
View Full Document

Ask a homework question - tutors are online