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

Info icon This 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];
Image of page 1

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

View Full Document Right Arrow Icon
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

{[ snackBarMessage ]}

What students are saying

  • Left Quote Icon

    As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

    Student Picture

    Kiran Temple University Fox School of Business ‘17, Course Hero Intern

  • Left Quote Icon

    I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

    Student Picture

    Dana University of Pennsylvania ‘17, Course Hero Intern

  • Left Quote Icon

    The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

    Student Picture

    Jill Tulane University ‘16, Course Hero Intern