4 -1 Chapter 5 The Divide-and-Conquer Strategy خوارزميات التقسيم والضم 4 -2 A simple example finding the maximum of a set S of n numbers 4 -3 A general divide-and-conquer algorithm Step 1: If the problem size is small, solve this problem directly; otherwise, split the original problem into 2 sub-problems with equal sizes. Step 2: Recursively solve these 2 sub-problems by applying this algorithm. Step 3: Merge the solutions of the 2 subproblems into a solution of the original problem. 4 -4 Algorithm Merge-Sort خوارزمية الترتيب بالدمج Input: A set S of n elements. Output: The sorted sequence of the inputs in nondecreasing order. Step 1: If |n|2, solve it directly. Step 2: Recursively apply this algorithm to solve the left half part and right half part of S, and the results are stored in n1 and n2, respectively. Step 3: Perform the two-way merge scheme on n1 and n2. Mergesort 5 Algorithm: Split array A[1..n] in two and make copies of each half in arrays B[1.. n/2 ] and C[1.. n/2 ] arrays B and Cذ Merge sorted arrays B and C into array A Pseudocode of Mergesort Pseudocode of Merge Time complexity: Θ(p+q) = Θ(n) comparisons Merge Sort – Example Original Sequence Sorted Sequence 18 26 32 6 43 15 9 1 1 6 9 15 18 26 32 6 43 15 9 1 6 18 26 18 26 32 6 43 15 9 1 18 26 6 32 18 26 32 6 43 15 9 1 26 32 6 18 26 32 6 43 15 9 1 18 Comp 122 32 18 26 1 9 15 43 32 43 15 43 43 43 1 9 15 9 1 Analysis of Merge Sort Running time T(n) of Merge Sort: Divide: computing the middle takes (1) Conquer: solving 2 subproblems takes 2T(n/2) Combine: merging n elements takes (n) Total: T(n) = (1) if n = 1 T(n) = 2T(n/2) + (n) if n > 1 T(n) = (n lg n) Comp 122 Quicksort 11 Select a pivot (partitioning element) Rearrange the list so that all the elements in the positions before the pivot are smaller than or equal to the pivot and those after the pivot are larger than or equal to the pivot Exchange the pivot with the last element in the first (i.e., ≤) sublist – the pivot is now in its final position Sort the two sublists recursively p A[i]≤p A[i]p Apply quicksort to sort the list 7 2 9 10 5 4 Design and Analysis of Algorithms – Chapter 5 pseudocode of quicksort: ALGORITHM Quicksort(A[l..r]) //Sorts a subarray by quicksort //Input: Subarray of array A[0..n − 1], defined by its left and right // indices l and r //Output: Subarray A[l..r] sorted in nondecreasing order if l < r s ←Partition(A[l..r]) //s is a split position Quicksort(A[l..s − 1]) Quicksort(A[s + 1..r]) Quicksort Example 13 Recursive implementation with the left most array entry selected as the pivot element. Design and Analysis of Algorithms – Chapter 5 Exercise : Apply quicksort to sort the list E, X, A,M, P, L, E in alphabetical order. Draw the tree of the recursive calls made.