MergeSort

# Memory memory complexity on not in place in on copy

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: rations in each pass – Main disadvantage to quicksort or heapsort – In-place variant exists, but large overhead In- ! Time Time complexity (worst case): O(n log n) log – For pre-sorted sequence, worse than insertion sort pre- ! ! ! ! Can be stable if merge() is stable Easier to implement than quicksort and heapsort In In practice slower that quicksort, but faster than heapsort heapsort Advantage: sequential access of data – Excellent for external (out-of-core) sorting (e.g. disk) (out-of(e.g. – Good cache usage 14 Merge Sort: improvements ! Inefficiency of merge() – Comparisons (i > mid) and (j > ub) Comparisons evaluate evaluate to FALSE most of the time Function merge (r, lb, mid, ub): memcpy(&tmp[lb], &r[lb], mid-lb+1); memcpy(&tmp[mid+1], &r[mid+1], ub-mid); i ← lb; j ← mid+1; lb; for for k ← lb to ub lb if if (i > mid) r[k] ← tmp[j++]; else else if (j > ub) r[k] ← tmp[i++]; tmp[i++]; else if (tmp[j] < tmp[i]) r[k] ← tmp[j++]; 15 else else r[k] ← tmp[i++]; Merge Sort: bitonic sort Use sentinel (as in insertion sort) Function bsmerge (r, lb, mid, ub): memcpy(&tmp[lb], &r[lb], mid-lb+1); j ← ub; for for k ← mid+1 to ub tmp[k] ← r[j]; // copy in reverse // j--; // // order i ← lb; j ← ub; lb; for for k ← lb to ub lb if if (tmp[j] < tmp[i]) r[k] ← tmp[j--]; else...
View Full Document

{[ snackBarMessage ]}

### What students are saying

• 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.

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

• 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.

Dana University of Pennsylvania ‘17, Course Hero Intern

• 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.

Jill Tulane University ‘16, Course Hero Intern