MergeSort

MergeSort - int ii for(i=0 i<n1 i s1[i]=s[i for(i=n1...

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

View Full Document Right Arrow Icon
How long does Merge Sort Take? -To figure this out, we use, “amortized time”. That is we find first the time spent in one element in the array and then multiply this by n (nElements) -copy operations: Divide → 3 copy operations Merge/Conquer → 3 comparisons -comparisons ~log(n) The number of comparisons is also the number of times an element is copied to the new array in the marge step -If there are n elements: Total Time = n(k1 log(n) + k2 log(n)) = n log(n)[2(k1) + k2] = O(n log(n)) Implementation void mergesort(int *s, in n) { //s is an array of n ints. Divide. Create s1 s2 if(n <= 1) { return; } int n1 = n/2; //sizeof s1 int n2 = n-n1; //sizeof s2 int *s1 = new int[n1]; int *s2 = new int[n2];
Background image of page 1

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

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

Unformatted text preview: int ii; for(i=0; i<n1; i++) { s1[i]=s[i]; } for(i=n1; i<n2; i++) { s2[i]=s[i]; } //call mergesort recursively mergesort(s1, n1); mergesort(s2, n2); //now s1 and s2 are sorted //put elements of s1 and s2 back into s int i1=0; //index s1 int i2=0; //index s2 //i is used as index for s //choose min element from s1 and s2 while(i1<n2 && i2<n2) { if(s1[i1] < s2[i2]) { s[i] = s1[i1]; i1++; } else { s[i] = s2[i2]; i2++; } i++; } //reached the end of either s1 or s2, copy the remaining elements for(/*empty*/ ; i1 < n1; i1++) { s[i] = s1[i1]; i++; } for(/*empty*/; i2 < n2; i2++) { s[i]=s2[i2]; i++; } //sorted //delete delete s1; delete s2; } //end mergesort...
View Full Document

This note was uploaded on 02/04/2012 for the course CS 251 taught by Professor Staff during the Fall '08 term at Purdue.

Page1 / 2

MergeSort - int ii for(i=0 i<n1 i s1[i]=s[i for(i=n1...

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