Download presentation
Presentation is loading. Please wait.
Published byἈλαλά Κούνδουρος Modified over 6 years ago
1
Mergesort Based on divide-and-conquer strategy
Divide the list into two smaller lists of about equal sizes Sort each smaller list recursively Merge the two sorted lists to get one sorted list How do we divide the list? How much time needed? How do we merge the two sorted lists? How much time needed?
2
First, the list is split into halves.
In order to analyze the merge_sort function, consider the two distinct processes that make up its implementation. First, the list is split into halves. We already computed (in a binary search) that we can divide a list in half lg(n) times where n is the length of the list. Not using the slice operator here.
3
In order to analyze the merge_sort function, consider the two distinct processes that make up its implementation. The second process is the merge. Each item in the list will eventually be processed and placed on the sorted list. So the merge operation which results in a list of size n, requires n operations. The result of this analysis is lg(n) splits, each of which costs n for a total of nlg(n) operations. A merge sort is an O(nlgn) algorithm.
4
Merge Sort Divide-and-conquer strategy
recursively mergesort the first half and the second half merge the two sorted halves together
8
How to merge? Input: two sorted arrays A and B
Output: an output sorted array C Three counters: Actr, Bctr, and Cctr initially set to the beginning of their respective arrays (1) The smaller of A[Actr] and B[Bctr] is copied to the next entry in C, and the appropriate counters are advanced (2) When either input list is exhausted, the remainder of the other list is copied to C
9
Example: Merge
10
Example: Merge... Running time analysis: Space requirement:
Clearly, merge takes O(m1 + m2) where m1 and m2 are the sizes of the two sublists. Space requirement: merging two sorted lists requires linear extra memory additional work to copy to the temporary array and back
11
def merge_sort(alist):
if len(alist) > 1: mid = len(alist) // 2 lefthalf = alist[:mid] righthalf = alist[mid:] merge_sort(lefthalf) merge_sort(righthalf) i,j,k = 0,0, while I < len(lefthalf) and j < len(righthalf): if lefthalf[i] < righthalf[j]: alist[k] = lefthalf[i] i += 1 else: alist[k] = righthalf[j] j += 1 k += 1 while i < len(lefthalf): i, k = i + 1, k + 1 while j < len(righthalf): j, k = j + 1, k + 1
12
Analysis of mergesort Let T(N) denote the worst-case running time of mergesort to sort N numbers. Assume that N is a power of 2. Divide step: O(1) time Conquer step: 2 T(N/2) time Combine step: O(N) time Recurrence equation: T(1) = 1 T(N) = 2T(N/2) + N
13
Solving the Recurrence Relation
Covered in Discrete Mathematics Other important recurrence relations T(n) = T(n – 1) + 1 O(n) T(n) = T(n/2) + 1 O(log n) T(n) = T(n – 1) + n O(n2)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.