5_onotation

# Foratotalofnn12comparisonsandmoves john edgar 52

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

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: arch?  !  Either the target is not in the array, or   !  It is found when the search space consists of one  element  !  How many times does the while loop iterate  in the worst case?  John Edgar 35 !  Each iteration of the while loop halves the search  space  !  For simplicity assume that n is a power of 2  ▪  So n = 2k (e.g. if n = 128, k = 7)  !  The first iteration halves the search space to n/2  !  After the second iteration the search space is n/4  !  After the kth iteration the search space consists of just one  element, since n/2k = n/n = 1  ▪  Because n = 2k, k = log2n  !  Therefore at most log2n iterations of the while loop are  made in the worst case!  John Edgar 36 !  Is the average case more like the best case or the  worst case?  !  What is the chance that an array element is the target  ▪  1/n the first time through the loop  ▪  1/(n/2) the second time through the loop  ▪  … and so on …  !  It is more likely that the target will be found as the  search space becomes small  !  That is, when the while loop nears its final iteration  !  We can conclude that the average case is more like the  worst case than the best case  John Edgar 37 n 10 100 1,000 10,000 100,000 1,000,000 10,000,000 John Edgar (3n+1)/4 8 76 751 7,501 75,001 750,001 7,500,001 log2(n) 3 7 10 13 17 20 24 38 !  As an example of algorithm analysis let's look at two  simple sorting algorithms  !  Selection Sort and  !  Insertion Sort  !  Calculate an approximate cost function for these  two sorting algorithms   !  By analyzing how many operations are performed by  each algorithm  !  This will include an analysis of how many times the  algorithms' loops iterate  John Edgar 40 !  Selection sort is a simple sorting algorithm  that repeatedly finds the smallest item  unsorted part  !  The array is divided into a sorted part and an  !  Repeatedly swap the first unsorted item with  the smallest unsorted item  !  Starting with the element with index 0, and  !  Ending with last but one element (index n – 1)  John Edgar 41 23 41 33 81 07 19 11 45 07 41 33 81 23 19 11 45 07 11 33 81 23 19 41 45 07 11 19 81 23 33 41 45 07 11 19 23 81 33 41 45 07 11 19 23 33 81 41 45 07 11 19 23 33 41 81 45 07 11 19 23 33 41 45 81 find smallest unsorted - 7 comparisons find smallest unsorted - 6 comparisons find smallest unsorted - 5 comparisons find smallest unsorted - 4 comparisons find smallest unsorted - 3 comparisons find smallest unsorted - 2 comparisons find smallest unsorted - 1 comparison John Edgar 42 Unsorted elements n n‐1 … 3 2 1 Comparis...
View Full Document

## This note was uploaded on 04/17/2010 for the course CMPT 11151 taught by Professor Gregorymori during the Spring '10 term at Simon Fraser.

Ask a homework question - tutors are online