Sorting1.4 - Merge Sort 88 52 14 31 25 98 30 23 62 79 Get...

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: Merge Sort 88 52 14 31 25 98 30 23 62 79 Get one friend to sort the first half. Get one friend to sort the second half. 25,31,52,88,98 CSE 2011 Prof. J. Elder Split Set into Two (no real work) 14,23,30,62,79 - 21 - Last Updated: 4/1/10 11:16 AM Merge Sort Merge two sorted lists into one 25,31,52,88,98 14,23,25,30,31,52,62,79,88,98 14,23,30,62,79 CSE 2011 Prof. J. Elder - 22 - Last Updated: 4/1/10 11:16 AM Merge-Sort Merge-sort on an input sequence S with n elements consists of three steps: Divide: partition S into two sequences S1 and S2 of about n/2 elements each Recur: recursively sort S1 and S2 Conquer: merge S1 and S2 into a unique sorted sequence Algorithm mergeSort(S) Input sequence S with n elements Output sequence S sorted if S.size() > 1 split(S, n/2) (S1, S2) mergeSort(S1) mergeSort(S2) merge(S1, S2, S) CSE 2011 Prof. J. Elder - 23 - Last Updated: 4/1/10 11:16 AM Merging Two Sorted Sequences The conquer step of merge-sort consists of merging two sorted sequences A and B into a sorted sequence S containing the union of the elements of A and B Merging two sorted sequences, each with n/2 elements takes O(n) time Normally, merging is not in-place: new memory must be allocated to hold S. It is possible to do in-place merging using linked lists. Code is more complicated Only changes memory usage by a constant factor CSE 2011 Prof. J. Elder - 24 - Last Updated: 4/1/10 11:16 AM Merging Two Sorted Sequences (As Arrays) Algorithm merge(S1, S2 , S): Input: Sorted sequences S1 and S2 and an empty sequence S, implemented as arrays Output: Sorted sequence S containing the elements from S1 and S2 i j0 while i < S1.size() and j < S2 .size() do if S1.get(i ) S2 .get(j ) then S.addLast(S1.get(i )) i i +1 else S.addLast(S2 .get(j )) j j +1 while i < S1.size() do S.addLast(S1.get(i )) i i +1 while j < S2 .size() do S.addLast(S2 .get(j )) j j +1 CSE 2011 Prof. J. Elder - 25 - Last Updated: 4/1/10 11:16 AM ...
View Full Document

This note was uploaded on 02/14/2012 for the course CSE 2011Z taught by Professor Elder during the Fall '11 term at York University.

Ask a homework question - tutors are online