lecture16

lecture16 - COMP 250 Winter 2010 16 - mergesort Feb 12,...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
COMP 250 Winter 2010 16 - mergesort Feb 12, 2010 Example 7: Mergesort In lecture 3, we saw the “insertion sort” algorithm for sorting n items. This algorithm was O ( n 2 ) and we saw that, in the worst case that the input elements are sorted in the wrong order, the algorithm requires n ( n - 1) 2 or n 2 2 n 2 or operations. Thus, not only is insertion sort O ( n 2 ), it is also Ω( n 2 ) – see Exercises 2. There are sorting algorithms run in time less than O ( n 2 ), even in the worst case that the input elements are sorted but in the wrong order. Today we will see one them, called mergesort . The idea of mergesort is simple. If there is just one number to sort ( n = 1), then do nothing. Otherwise, partition the list of n elements into two lists of size n/ 2 and n/ 2 , sort each of these two lists, and then merge the two sorted lists. The ±oor and ceiling notation is used for the case that n is odd, and so the two sets are of di²erent sizes (even and odd). For example, suppose we have a list 8 , 10 , 3 , 11 , 6 , 1 , 9 , 7 , 13 , 2 , 5 , 4 , 12 . We partition it into two lists < 8 , 10 , 3 , 11 , 6 , 1 , 8 > < 9 , 7 , 13 , 2 , 5 , 4 , 12 > . and sort these (by applying mergesort recursively): < 1 , 3 , 6 , 8 , 10 , 11 > < 2 , 4 , 5 , 7 , 9 , 12 , 13 > . Then, we merge these two lists
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 4

lecture16 - COMP 250 Winter 2010 16 - mergesort Feb 12,...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online