lecture-12

# Last mergethearray n rst mid last cpsc 223 fall

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: rst, int last) { if(ﬁrst &lt; last) { int mid = (ﬁrst + last) / 2; Mergesort(theArray, n, ﬁrst, mid); Mergesort(theArray, n, mid + 1, last); Merge(theArray, n, ﬁrst, mid, last); } } CPSC 223  ­ ­ Fall 2010 7 Mergesort (based on textbook) void Merge(Entry theArray, int n, int ﬁrst, int mid, int last) { Entry tmpArray[n]; int ﬁrst1 = ﬁrst, ﬁrst2 = mid + 1, i = ﬁrst1; for(; ﬁrst1 &lt;= mid &amp;&amp; ﬁrst2 &lt;= last; i++) { if(theArray[ﬁrst1] &lt; theArray[ﬁrst2]) tmpArray[i] = theArray[ﬁrst1++]; else tmpArray[i] = theArray[ﬁrst2++]; } for(; ﬁrst1 &lt;= tmpArray[i] for(; ﬁrst2 &lt;= tmpArray[i] mid; i++, ﬁrst1++) = theArray[ﬁrst1]; last; i++, ﬁrst2++) = theArray[ﬁrst2]; for(int j = ﬁrst; j &lt;= last; j++) theArray[j] = tmpArray[j]; // copy remaining from ﬁrst half // copy remaining from sec. half // copy tmpArray to the array } CPSC 223  ­ ­ Fall 2010 8 4 10/12/10 Mergesort The merge step •  Assume number of elements to be merged is n –  n = length of ﬁrst half + length of second half •  The me...
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