lecture-12

Each time we call mergesort twice halving the list

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: rge step requires –  n – 1 comparisons (worst case) –  n moves from the original array to the temp array –  n moves from the temp array to the original array •  So merge costs 3n – 1 •  Which is O(n) CPSC 223  ­ ­ Fall 2010 9 Mergesort •  How expensive is mergesort? –  Each time we call mergesort twice (halving the list) –  Assume n items in the list –  The recursion goes approximately log2n levels deep –  At each level the merges cost a total of O(n) •  So mergesort is O(nlog n) !!! 29 10 14 13 2 levels of recursion 29 10 29 Ini3al list (n=4) Split 14 13 10 14 CPSC 223  ­ ­ Fall 2010 13 Split 10 5 10/12/10 Mergesort Why log2n levels of recursion? –  Each level adds twice the number of sublists –  Each sublist is half the size of the previous ones –  We stop “expanding” when sublists are of size 1 •  Lets say n = 8 –  The 1st level results in sublists of size n / 21 –  The 2nd level results in sublists of size n / 22 –  The 3rd level results in sublists of size n / 23 •  We stop the recursion when n / 2r = 1 –  This means that n = 2r –  So the number of levels (merges) is log2 n = r CPSC 223  ­ ­ Fall 2010 11 Mergesort Mergesort is a “fast” sort •  But it comes at a cost ... –  Merging uses temporary space (tmpArray) –  We’re using more space to obtain time efficiency CPSC 223  ­...
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