MergeSort

1 r0 7 1 j 3 5 5 2 3 4 6 tmp4 7 2 3 3 4 5 5 6

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: erge Merge sort: example merge i tmp[0, tmp[0, 3] 1 r[0, 7] 1 j 3 5 5 2 3 4 6 tmp[4, 7] 2 3 3 4 5 5 6 Complexity: Complexity: O(n) 7 Merge Merge Sort: example 3 1 6 3 2 5 4 5 3 1 6 3 2 5 4 5 1 6 3 2 5 4 5 1 6 3 2 5 4 5 3 6 3 2 5 4 5 3 3 1 8 Merge Merge Sort: example 1 3 1 6 3 3 2 5 4 5 3 6 2 5 4 5 4 5 1 3 3 6 2 5 1 3 3 6 2 5 1 3 3 6 2 5 4 4 5 5 9 Merge Merge Sort: example 1 3 3 6 2 5 4 1 3 3 6 2 5 4 1 3 3 6 2 5 4 1 3 3 6 2 5 4 1 3 3 6 2 4 5 5 5 5 5 5 10 Merge Merge Sort: example 1 3 3 6 2 4 5 5 1 2 3 3 4 5 5 6 11 Merge Sort: iterative algorithm ! Bottom-up process – Leaf nodes: Consider original array as n subarrays of size 1 – Scan through array performing 1-by-1 mergers to to produce n/2 ordered subarrays of 2 elements – Scan through array performing 2-by-2 mergers to produce n/4 ordered subarrays of 4 elements –… – Scan through array performing n/2-by-n/2 merger to produce the final ordered array of n elements 12 Iterative Iterative Merge Sort: implementation Iteratively Iteratively merge sort n integers r[0, n-1] in 1] ascending ascending order Function imergesort (r, n): size size ← 1 while size < n i←0 while while i < n – size merge(r, i, i+size-1, 1, min(i+2*size min(i+2*size-1, n-1)); i ← i + 2*size size size ← 2*size; 13 Merge Sort comments ! Memory Memory complexity: O(n), not in-place in– O(n) copy ope...
View Full Document

Ask a homework question - tutors are online