280 likes | 446 Views
Divide-and conquer is a general algorithm design approach: Divide : divide the input data S in two disjoint subsets S 1 and S 2 Recur : solve the sub-problems associated with S 1 and S 2 Conquer : combine the solutions for S 1 and S 2 into a solution for S
E N D
Divide-and conquer is a general algorithm design approach: Divide: divide the input data S in two disjoint subsets S1and S2 Recur: solve the sub-problems associated with S1and S2 Conquer: combine the solutions for S1and S2 into a solution for S The base case for the recursion are sub-problems of size 0 or 1 Divide-and-Conquer Approach
Merge Sort as a Divide and Conquer Approach • Merging a two lists of one element each is the same as sorting them. • Merge sort divides up an unsorted list until the above condition is met and then sorts the divided parts back together in pairs. • Specifically this can be done by recursively dividing the unsorted list in half, merge sorting the right side then the left side and then merging the right and left back together.
Merge-sort on an input List (Array) S with n elements consists of three steps: Divide: partition S into two lists S1and S2 of about n/2 elements each Recur: recursively sort S1and S2 Conquer: merge S1and S2 into a unique sorted list. Merge-Sort AlgorithmmergeSort(S, C) InputList S with n elements, comparator C Output List S sorted • according to C ifS.size() > 1 (S1, S2) partition(S, n/2) mergeSort(S1, C) mergeSort(S2, C) S merge(S1, S2)
Merging Two Sorted Sequences Algorithmmerge(A, B) Inputsequences A and B withn/2 elements each Outputsorted sequence of A B Sempty sequence whileA.isEmpty()B.isEmpty() ifA.first().element()<B.first().element() S.insertLast(A.remove(A.first())) else S.insertLast(B.remove(B.first())) whileA.isEmpty()S.insertLast(A.remove(A.first())) whileB.isEmpty()S.insertLast(B.remove(B.first())) return S • The conquer step of merge-sort consists of merging two sorted sequences A and B into a sorted sequence S containing the union of the elements of A and B • Example: L1 = { 3 8 9 } L2 = { 1 5 7 } merge(L1, L2) = { 1 3 5 7 8 9 }
Merging (cont.) X: Y: Result:
Merging (cont.) X: Y: Result:
Merging (cont.) X: Y: Result:
Merging (cont.) X: Y: Result:
Merging (cont.) X: Y: Result:
Merging (cont.) X: Y: Result:
Merging (cont.) X: Y: Result:
Merging (cont.) X: Y: Result:
Merging (cont.) X: Y: Result:
Merge Sort Example Merge
Merge Sort Example Merge
Merge Sort Example Merge
Merge Sort Example Merge
AlgorithmMERGESORT Input: An array A[1..n] of n elements. Output:A[1..n] sorted in nondecreasing order. mergesort(A, 1, n) Procedure mergesort(A, low, high) 1. if low < high then 2. mid (low + high) / 2 T(1) 3. mergesort(A, low, mid) T(n/2) 4. mergesort(A, mid + 1, high) T(n/2) 5. MERGE (A, low, mid, high) T(n) 6. end if Use: Linear-time merge subroutine.
Merge Sort Analysis T(N) = 2T(N/2) + N = O(N logN)