2/26/2016. Divide and Conquer. Chapter 6. The Divide and Conquer Paradigm

Size: px
Start display at page:

Download "2/26/2016. Divide and Conquer. Chapter 6. The Divide and Conquer Paradigm"

Transcription

1 Divide and Conquer Chapter 6 Divide and Conquer A divide and conquer algorithm divides the problem instance into a number of subinstances (in most cases 2), recursively solves each subinsance separately, and then combines the solutions to the subinstances to obtain the solution to the original problem instance. CS3330: Algorithms Divide and Conquer Consider the problem of finding both the minimum and maximum in an array of integers A[ n] and assume for simplicity that n is a power of 2. Divide the input array into two halves A[ n2] and A[(n2)+ n], find the minimum and maximum in each half and return the minimum of the two minima and the maximum of the two maxima. Divide and Conquer Input: An array A[ n] of n integers; Output: (x, y): the minimum and maximum integers in A;. minmax(, n); minmax(low, high). if high=low there is only number 2. return (A[low], A[low]); 3. if high=low+ there are only 2 numbers 4. if A[low]<A[high] return (A[low], A[high]); 5. else return(a[high], A[low]); 6. mid(low+high)2 ; more than two numbers 7. (x, y ) minmax(low, mid); 8. (x 2, y 2 ) minmax(mid+, high); 9. return(min{x, x 2 }, max{y, y 2 }); Divide and Conquer How many comparisons does this algorithm need? Given an array A[ n] of n elements, where n is a power of 2, it is possible to find both the minimum and maximum of the elements in A using only.5n 2 element comparisons. Let C(n) be the maximum number of comparisons the algorithm needs for n numbers. C() = 0, C(2) = C(n) = 2C(n2) + 2. Then C(n) =.5n 2 for (power of 2) n >. The Divide and Conquer Paradigm The divide step: the input is partitioned into p parts, each of size strictly less than n. The conquer step: performing p recursive call(s) if the problem size is greater than some predefined threshold n 0. The combine step: the solutions to the p recursive call(s) are combined to obtain the desired output.

2 Sorting algorithms Insertion, selection and bubble sort have quadratic worst case performance The faster comparison based algorithm? O(nlogn) Heapsort, Mergesort, Quicksort Merge Sort An example of divide and conquer technique Problem: Given n elements, sort elements into nondecreasing order Divide and Conquer: If n= terminate (every one element list is already sorted) If n>, partition elements into two or more subcollections; sort each; combine into a single sorted list How do we partition? Partitioning Choice First n elements into set A, last element set B Sort A using this partitioning scheme recursively B already sorted Combine A and B using method Insert() (= insertion into sorted array) Leads to recursive version of InsertionSort() Number of comparisons: O(n 2 ) Best case = n Worst case = c n i 2 n( n ) i 2 Divide Conquer View of Insertion Sort insertion_sort(int [] A, int n) { Pre: 0 <= n < A.length Post: A[0..n] is sorted if (n == 0) return; } divide: do nothing Now we have two parts: A[0..n-2] and A[n-] conquer: insertion_sort(a, n-); combine: insert(a, n-, A[n-]); insert(a, m, x) inserts x into A[0..m-] to keep it sorted. Partitioning Choice 2 Put element with largest key in B, remaining elements in A Sort A recursively To combine sorted A and B, append B to sorted A Use Max() to find largest element recursive SelectionSort() Use bubbling process to find and move largest element to right most position recursive BubbleSort() All O(n 2 ) Divide Conquer View of Selection Sort selection_sort(int [] A, int n) { Pre: 0 <= n < A.length Post: A[0..n] is sorted if (n == 0) return; } divide: int max = maxposition(a, n) ; it returns the position of max element exchange(a, n, max); Now we have two parts: A[0..n-2] and A[n-] conquer: selection_sort(a, n-); combine: do nothing. 2

3 Partitioning Choice 3 Let s try to achieve balanced partitioning A gets n2 elements, B gets the rest half Sort A and B recursively Combine sorted A and B using a process called merge, which combines two sorted lists into one How? We will see soon Mergesort Divide the array into two equally sized halves Recursively sort the halves Merge the sorted halves Example Partition into lists of size n2 [0, 4, 6, 3, 8, 2, 5, 7] Merge Example Cont d [2, 3, 4, 5, 6, 7, 8, 0 ] [0, 4, 6, 3] [8, 2, 5, 7] [3, 4, 6, 0] [2, 5, 7, 8] [0, 4] [6, 3] [8, 2] [5, 7] [4] [0] [3][6] [2][8] [5][7] [4, 0] [3, 6] [2, 8] [5, 7] [4] [0] [3][6] [2][8] [5][7] Merging The key to Merge Sort is merging two sorted lists into one, such that if you have two lists X (x x 2 x m ) and Y(y y 2 y n ) the resulting list is Z(z z 2 z m+n ) Example: X = { } Y = { 5 7 } merge(x, Y) = { } Merging X: Y: Result: 3

4 Merging (cont.) Merging (cont.) X: Y: X: Y: Result: Result: 3 Merging (cont.) Merging (cont.) X: Y: X: Y: Result: 3 5 Result: Merging (cont.) Merging (cont.) X: 54 Y: X: 54 Y: 75 Result: Result:

5 Merging (cont.) Merging (cont.) X: Y: 75 X: Y: Result: Result: Static Method mergesort() Evaluation Public static void mergesort(comparable []a, int left, int right) { sort a[left:right] using b[left:right] if (left < right) { at least two elements int mid = (left+right)2; midpoint mergesort(a, left, mid); mergesort(a, mid +, right); merge(a, b, left, mid, right); merge from a to b copy(b, a, left, right); copy result back to a } } Recurrence equation: Assume n is a power of 2 c if n= T(n) = 2T(n2) + c 2 n if n>, n=2 k By Substitution: T(n) = 2T(n2) + c 2 n T(n2) = 2T(n4) + c 2 n2 T(n) = 4T(n4) + 2 c 2 n T(n) = 8T(n8) + 3 c 2 n T(n) = 2 i T(n2 i ) + ic 2 n Solution Assuming n = 2 k, expansion halts when we get T() on right side; this happens when i=k T(n) = 2 k T() + kc 2 n Since 2 k =n, we know k=logn; since T() = c, we get T(n) = c n + c 2 nlogn; thus an upper bound for T mergesort (n) is O(nlogn) Implementing Merge Sort There are two basic ways to implement merge sort: In Place: Merging is done with only the input array Pro: Requires only the space needed to hold the array Con: Takes longer to merge because if the next element is in the right side then all of the elements must be moved down. Double Storage: Merging is done with a temporary array of the same size as the input array. Pro: Faster than In Place since the temp array holds the resulting array until both left and right sides are merged into the temp array, then the temp array is appended over the input array. Con: The memory requirement is doubled. 5

6 Variants and Applications There are other variants of Merge Sorts including bottom-up merge sort, k-way merge sorting, but the common variant is the Double Memory Merge Sort. Though the running time is O(n log n) and runs much faster than insertion sort and bubble sort, merge sort s large memory demands makes it not very practical for main memory sorting. Merge Sort is the major method for external sorting, parallel algorithms, and sorting circuits. Bottom up Merge Sort Sublists are always of size 2 k, except the last [2, 3, 4, 5, 6, 7, 8, 0 ] [3, 4, 6, 0] [2, 5, 7, 8] [4, 0] [3, 6] [2, 8] [5, 7] [4] [0] [3][6] [2][8] [5][7] Bottom up Merge Sort Sublists are always of size 2 k, except the last Bottom up Merge Sort Sublists are always of size 2 k, except the last [2, 3, 4, 5, 6, 8, 0 ] [2, 3, 4, 6, 8, 0 ] [3, 4, 6, 0] [2, 5, 8] [3, 4, 6, 0] [4, 0] [3, 6] [2, 8] [4] [0] [3][6] [2][8] [5] [4, 0] [3, 6] [2, 8] [4] [0] [3][6] [2][8] Bottom up Merge Sort Sublists are always of size 2 k, except the last [2, 3, 4, 6, 0 ] [3, 4, 6, 0] [4, 0] [3, 6] [4] [0] [3][6] [2] Quicksort Algorithm Given an array of n elements (e.g., integers): If array only contains one element, return Else pick one element to use as pivot. Partition elements into two sub arrays: Elements less than or equal to pivot Elements greater than pivot Quicksort two sub arrays Return results 6

7 Example We are given array of n integers to sort: Pick Pivot Element There are a number of ways to pick the pivot element. In this example, we will use the first element in the array: Partitioning Array 0. = left+; = right; Given a pivot, partition the elements of the array such that the resulting array consists of:. One sub array that contains elements >= pivot 2. Another sub array that contains elements < pivot The sub arrays are stored in the original data array. Partitioning loops through, swapping elements belowabove pivot = left+; = right;. While data[] <= data[pivot] = left+; = right;. While data[] <= data[pivot]

8 0. = left+; = right;. While data[] <= data[pivot] = left+; = right;. While data[] <= data[pivot] While data[] > data[pivot] = left+; = right;. While data[] <= data[pivot] While data[] > data[pivot] = left+; = right;. While data[] <= data[pivot] While data[] > data[pivot] If < swap data[] and data[] = left+; = right;. While data[] <= data[pivot] While data[] > data[pivot] If < swap data[] and data[] 0. = left+; = right;. While data[] <= data[pivot] While data[] > data[pivot] If < swap data[] and data[] 4. If >, go to

9 0. = left+; = right;. While data[] <= data[pivot] While data[] > data[pivot] If < swap data[] and data[] 4. If >, go to. 5. Swap data[] and data[pivot_index] 0. = left+; = right;. While data[] <= data[pivot] While data[] > data[pivot] If < swap data[] and data[] 4. If >, go to. 5. Swap data[] and data[pivot_index] 6. Return pivot_index = Partition Result What is best case running time? <= data[pivot] > data[pivot] Recursive calls on two sides to get a sorted array. What is best case running time? Recursion:. Partition splits array in two sub arrays of size n2 2. Quicksort each sub array What is best case running time? Recursion:. Partition splits array in two sub arrays of size n2 2. Quicksort each sub array Depth of recursion tree? 9

10 What is best case running time? Recursion:. Partition splits array in two sub arrays of size n2 2. Quicksort each sub array Depth of recursion tree? O(log 2 n) What is best case running time? Recursion:. Partition splits array in two sub arrays of size n2 2. Quicksort each sub array Depth of recursion tree? O(log 2 n) Number of accesses in partition? What is best case running time? Recursion:. Partition splits array in two sub arrays of size n2 2. Quicksort each sub array Depth of recursion tree? O(log 2 n) Number of accesses in partition? O(n) Best case running time: O(n log 2 n) Best case running time: O(n log 2 n) Worst case running time? Best case running time: O(n log 2 n) Worst case running time? Recursion:. Partition splits array in two sub arrays: one sub array of size 0 the other sub array of size n 2. Quicksort each sub array Depth of recursion tree? 0

11 Best case running time: O(n log 2 n) Worst case running time? Recursion:. Partition splits array in two sub arrays: one sub array of size 0 the other sub array of size n 2. Quicksort each sub array Depth of recursion tree? O(n) Best case running time: O(n log 2 n) Worst case running time? Recursion:. Partition splits array in two sub arrays: one sub array of size 0 the other sub array of size n 2. Quicksort each sub array Depth of recursion tree? O(n) Number of accesses per partition? Best case running time: O(n log 2 n) Worst case running time? Recursion:. Partition splits array in two sub arrays: one sub array of size 0 the other sub array of size n 2. Quicksort each sub array Depth of recursion tree? O(n) Number of accesses per partition? O(n) Best case running time: O(n log 2 n) Worst case running time: O(n 2 )!!! Best case running time: O(n log 2 n) Worst case running time: O(n 2 )!!! What can we do to avoid worst case? Randomly pick a pivot Bad divide: T(n) = T() + T(n ) + n O(n 2 ) Good divide: T(n) = T(n2) + T(n2) + n O(n log 2 n) Random divide: Suppose on average one bad divide followed by one good divide. T(n) = T() + T(n ) + n = T() + 2T((n )2) + 2n T(n) = 2n + 2T((n )2) is still O(n log 2 n)

12 Improved Pivot Selection Pick median value of three elements from data array: data[0], data[n2], and data[n ]. Use this median value as pivot. For large arrays, use the median of three medians from {data[0], data[], data[2]}, {data[n2 ], data[n2], data[n2+]}, and {data[n 3], data[n 2], data[n ]}. Improving Performance of Quicksort Improved selection of pivot. For sub arrays of size 00 or less, apply brute force search, such as insert sort. Sub array of size : trivial Sub array of size 2: if(data[first] > data[second]) swap them Sub array of size 3: left as an exercise. Improving Performance of Quicksort Improved selection of pivot. For sub arrays of size 00 or less, apply brute force search, such as insert sort. Test if the sub array is already sorted before recursive calls. Don t pick out the pivot (avoiding the last swap). 0. = left+; = right;. while (data[] <= data[pivot] ++; 2. while (data[] > data[pivot]) --; 3. if ( < ) swap data[] and data[]; 4. if ( > ) go to. 5. swap data[] and data[pivot_index]; not needed 6. return ; pivot_index = Divide and Conquer Simple Divide Fancy Divide Uneven Divide vs n Insert Sort Selection Sort Even Divide n2 vs n2 Merge Sort Quick Sort Stable Sorting Maintains the original relative positioning of equivalent values InsertSort, SelectSort, BubbleSort are stable Heapsort is not stable Mergesort is stable Quicksort is not stable 2

13 How Fast Can We Sort? Selection Sort, Bubble Sort, Insertion Sort: O(n 2 ) Heap Sort, Merge sort: O(nlogn) Quicksort: O(nlogn) - average What is common to all these algorithms? Make comparisons between input elements a i < a j, a i a j, a i = a j, a i a j, or a i >a j Comparison based Sorting Comparison sort Only comparison of pairs of elements may be used to gain order information about a sequence. Hence, a lower bound on the number of comparisons will be a lower bound on the complexity of any comparison based sorting algorithm. All our sorts have been comparison sorts The best worst case complexity so far is (n lg n) (e.g., merge sort). We prove a lower bound of (n lg n) for any comparison sort: merge sort and heapsort are optimal. The idea is simple: there are n! outcomes, so we need a tree with n! leaves, and therefore log(n!) = n log n. 73 Decision Tree For insertion sort operating on three elements. :2 > 2:3 :3 >,2,3 :3 2,,3 2:3 > >,3,2 3,,2 2,3, 3,2, Contains 3! = 6 leaves. Simply unroll all loops for all possible inputs. Node i:j means compare A[i] to A[j]. Leaves show outputs; No two paths go to same leaf! Decision Tree (Contd.) Execution of sorting algorithm corresponds to tracing a path from root to leaf. The tree models all possible execution traces. At each internal node, a comparison a i a j is made. If a i a j, follow left subtree, else follow right subtree. View the tree as if the algorithm splits in two at each node, based on information it has determined up to that point. When we come to a leaf, ordering a () a (2) a (n) is established. A correct sorting algorithm must be able to produce any permutation of its input. Hence, each of the n! permutations must appear at one or more of the leaves of the decision tree. A Lower Bound for Worst Case Worst case no. of comparisons for a sorting algorithm is Length of the longest path from root to any of the leaves in the decision tree for the algorithm. Which is the height of its decision tree. A lower bound on the running time of any comparison sort is given by A lower bound on the heights of all decision trees in which each permutation appears as a reachable leaf. Optimal sorting for three elements Any sort of six elements has 5 internal nodes. :2 > 2:3 :3 >,2,3 :3 2,,3 2:3 > >,3,2 3,,2 2,3, 3,2, There must be a worst-case path of length 3. 3

14 A Lower Bound for Worst Case Theorem: Any comparison sort algorithm requires (n lg n) comparisons in the worst case. Proof: Suffices to determine the height of a decision tree. The number of leaves is at least n!(# outputs) The number of internal nodes n! The height is at least log (n! ) = (n lg n) Can we do better? Linear time sorting algorithms Counting Sort Bucket sort Radix Sort Make certain assumptions about the data Linear sorts are NOT comparison sorts 80 Counting Sort Assumptions: n integers which are in the range [0... r] r is in the order of n, that is, r=o(n) Idea: For each element x, find the number of occurrences of x and store it in the counter Place x into its correct position in the output array using the counter. Step (i.e., frequencies) (r=6) 8 82 Step 2. int index = 0; 2. for i= to max_value 3. for j = to counter[i] 4. values[index++] = i; Copy value iinto the array counts[i] times When an element has other info Step : Create a queue for each key. When an element is inserted, the key counter increases by one and the element is stored in the queue. Step 2: For each key ifrom small to big, the elements in the queue iis inserted into the array.. int index = 0; 2. for i= 0 to max_value 3. for j = to counter[i] 4. values[index++] = removefirst(queue[i]);

15 Analysis of Counting Sort Overall time: O(n + r) Step : O(n) Step 2: O(n + r) Space: O(n+r) In practice we use COUNTING sort when r = O(n) running time is O(n) 85 Bucket Sort Assumption: the input is generated by a random process that distributes elements uniformly over a range R = [a..b] Idea: Divide R into k equal sized buckets (k=θ(n)) Distribute the n input values into the buckets Sort each bucket (e.g., using quicksort or bucket sort) Go through the buckets in order, listing elements in each one Similar idea to sort post office mails, where k = 0. Input: A[0.. (n-)], where a A[i] b for all i Output: elements A[i] sorted 86 Example Bucket Sort R = [ ] Example Bucket Sort A B Distribute Into buckets Sort within each bucket Example Bucket Sort Concatenate the lists from 0 to k together, in order Alg.: BUCKET SORT(A, n) Analysis of Bucket Sort for i to n do insert A[i] into list B[ k*a[i] ] for i 0 to k - do sort list B[i] with quicksort sort concatenate lists B[0], B[],..., B[n -] together in order return the concatenated lists O(n) k O(nk log(nk)) =O(nlog(nk) O(k) O(n) (if k=θ(n)) 5

16 Counting Sort vs Bucket Sort Counting sort uses queues while Bucket Sort uses buckets similar data structures. The queues used by Counting sort store the elements of the same key they are already sorted. The buckets used by Bucket Sort store the elements sharing one feature of the keys they need be further sorted. Both are stable sorting algorithms if Bucket Sort uses stable sorting for each bucket. Radix Sort Represents keys as d digit numbers in some base k key = x x 2...x d where 0 x i k Example: key=54 key 0 = 5, d=3, k=0 where 0 x i 9 92 Assumptions d=o() and k =O(n) Radix Sort Sorting looks at one column at a time For a d digit number, sort the least significant digit first Continue sorting on the next least significant digit, until all digits have been sorted Requires only d passes through the list RADIX SORT Alg.: RADIX SORT(A, d) for i to d do use a stable sort to sort array A on digit i (stable sort: preserves order of identical elements) Analysis of Radix Sort Given n numbers of d digits each, where each digit may take Integer Addition Addition. Given two n-bit integers a and b, compute a + b. Grade-school. (n) bit operations. up to k possible values, RADIX SORT correctly sorts the numbers in O(d(n+k)), or O(n) if d = O() and k = O(n) One pass of sorting per digit takes O(n+k) assuming that we use counting sort There are d passes (for each digit) Remark. Grade-school addition algorithm is optimal

17 Integer Multiplication Divide-and-Conquer Multiplication: Warmup Multiplication. Given two n-bit integers a and b, compute a b. Grade-school. (n 2 ) bit operations. To multiply two n-bit integers a and b: Multiply four ½n-bit integers, recursively. Add and shift to obtain result Ex. a 2 n 2 a a 0 b 2 n 2 b b 0 ab 2 n 2 a a 0 2 n 2 b b 0 2 n a b 2 n 2 a b 0 a 0 b a 0 b 0 a = 0000 b = 0000 a a 0 b b 0 T(n) 4Tn2 (n) T(n) (n2 ) recursive calls add, shift Q. Is grade-school multiplication algorithm optimal? Recursion Tree Karatsuba Multiplication 0 if n 0 T(n) 4T(n2) n otherwise T(n) lg n T(n) n 2 k n 2 lg n 2n 2 n k 0 2 n To multiply two n-bit integers a and b: Add two ½n bit integers. Multiply three ½n-bit integers, recursively. Add, subtract, and shift to obtain result. a 2 n 2 a a 0 T(n2) T(n2) T(n2) T(n2) 4(n2) b 2 n 2 b b 0 ab 2 n a b 2 n 2 a b 0 a 0 b a 0 b 0 2 n a b 2 n 2 (a a 0 )(b b 0 ) a b a 0 b 0 a 0 b T(n4) T(n4) T(n4) T(n4)... T(n4) T(n4) T(n4) T(n4) 6(n4) T(n 2 k ) 4 k (n 2 k ) T(2) T(2) T(2) T(2)... T(2) T(2) T(2) T(2) 4 lg n () Karatsuba Multiplication Karatsuba: Recursion Tree To multiply two n-bit integers a and b: Add two ½n bit integers. Multiply three ½n-bit integers, recursively. Add, subtract, and shift to obtain result. 0 if n 0 T(n) 3T(n2) n otherwise T(n) lg n T(n) n 3 k 3 lg n 2 n 2 3 k 0 3nlg 3 2n 2 n a 2 n 2 a a 0 b 2 n 2 b b 0 ab 2 n a b 2 n 2 a b 0 a 0 b a 0 b 0 T(n2) T(n2) T(n2) 3(n2) 2 n a b 2 n 2 (a a 0 )(b b 0 ) a b a 0 b 0 a 0 b T(n4) T(n4) T(n4) T(n4) T(n4) T(n4) T(n4) T(n4) T(n4) 9(n4) Theorem. [Karatsuba-Ofman 962] Can multiply two n-bit integers in O(n.585 ) bit operations.... T(n 2 k )... 3 k (n 2 k ) T n2 T(n) Tn2 T n2 (n) T (n) O(n lg 3 ) O(n.585 ) recursive calls add, subtract, shift... T(2) T(2) T(2) T(2)... T(2) T(2) T(2) T(2)... 3 lg n ()

18 Dot Product Matrix Multiplication Dot product. Given two length n vectors a and b, compute c = a b. Grade-school. (n) arithmetic operations. n a b a i b i a b a b (.70.30) (.20.40) (.0.30).32 i Matrix multiplication. Given two n-by-n matrices A and B, compute C = AB. Grade-school. (n 3 ) arithmetic operations. c c 2 c n a a 2 a n b b 2 b n c 2 c 22 c 2n a 2 a 22 a 2n b 2 b 22 b 2n c n c n2 c nn a n a n2 a nn b n b n2 b nn n c ij a ik b kj k Remark. Grade-school dot product algorithm is optimal. Q. Is grade-school matrix multiplication algorithm optimal? Block Matrix Multiplication Matrix Multiplication: Warmup C A A 2 B B To multiply two n-by-n matrices A and B: Divide: partition A and B into ½n-by-½n blocks. Conquer: multiply 8 pairs of ½n-by-½n matrices, recursively. Combine: add appropriate products using 4 matrix additions. C C 2 A C A B A 2 B 2 A 2 B B 2 C C 2 A B 2 A 2 B 2 C 22 A 2 A 22 B 2 B C 2 A 2 B A 22 B 2 C 22 A 2 B 2 A 22 B 22 C A B A 2 B T(n) 8T n2 (n2 ) T(n) (n 3 ) recursive calls add, form submatrices Fast Matrix Multiplication Fast Matrix Multiplication Key idea. multiply 2-by-2 blocks with only 7 multiplications. C C 2 A A 2 B B 2 C 2 C 22 A 2 A 22 B 2 B 22 P A (B 2 B 22 ) P 2 ( A A 2 ) B 22 To multiply two n-by-n matrices A and B: [Strassen 969] Divide: partition A and B into ½n-by-½n blocks. Compute: 4 ½n-by-½n matrices via 0 matrix additions. Conquer: multiply 7 pairs of ½n-by-½n matrices, recursively. Combine: 7 products into 4 terms using 8 matrix additions. C P 5 P 4 P 2 P 6 C 2 P P 2 C 2 P 3 P 4 C 22 P 5 P P 3 P 7 7 multiplications. 8 = additions and subtractions. P 3 ( A 2 A 22 ) B P 4 A 22 (B 2 B ) P 5 ( A A 22 ) (B B 22 ) P 6 ( A 2 A 22 ) (B 2 B 22 ) P 7 ( A A 2 ) (B B 2 ) Analysis. Assume n is a power of 2. T(n) = # arithmetic operations. T(n) 7T n2 (n2 ) T(n) (n log 2 7 ) O(n 2.8 ) recursive calls add, subtract

19 Fast Matrix Multiplication Fast Matrix Multiplication: Practice To multiply two n-by-n matrices A and B: [Strassen 969] T(n) 7T n2 (n2 ) T(n) (n log 2 7 ) O(n 2.8 ) recursive calls add, subtract Implementation issues. Sparsity. Caching effects. Numerical stability. Odd matrix dimensions. Crossover to classical algorithm around n = 28. Common misperception. Strassen is only a theoretical curiosity. Apple reports 8x speedup on G4 Velocity Engine when n 2,500. Range of instances where it's useful is a subject of controversy. Remark. Can "Strassenize" Ax = b, determinant, eigenvalues, SVD, Fast Matrix Multiplication: Theory Fast Matrix Multiplication: Theory Q. Multiply two 2-by-2 matrices with 7 scalar multiplications? A. Yes! [Strassen 969] (n log 2 7 ) O(n ) Q. Multiply two 2-by-2 matrices with 6 scalar multiplications? A. Impossible. [Hopcroft and Kerr 97] (n log 2 6 ) O(n 2.59 ) Q. Two 3-by-3 matrices with 2 scalar multiplications? A. Also impossible. (n log 3 2 ) O(n 2.77 ) Begun, the decimal wars have. [Pan, Bini et al, Schönhage, ] Two 20-by-20 matrices with 4,460 scalar multiplications. O(n ) O(n Two 48-by-48 matrices with 47,27 scalar multiplications. ) A year later. O(n ) December, 979. O(n ) January, 980. O(n ) Best known. O(n ) [Coppersmith-Winograd, 987] Conjecture. O(n 2+ ) for any > 0. Caveat. Theoretical improvements to Strassen are progressively less practical. 2 9

Presentation for use with the textbook, Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, Merge Sort & Quick Sort

Presentation for use with the textbook, Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, Merge Sort & Quick Sort Presentation for use with the textbook, Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015 Merge Sort & Quick Sort 1 Divide-and-Conquer Divide-and conquer is a general algorithm

More information

Chapter 5. Divide and Conquer. Slides by Kevin Wayne. Copyright 2005 Pearson-Addison Wesley. All rights reserved.

Chapter 5. Divide and Conquer. Slides by Kevin Wayne. Copyright 2005 Pearson-Addison Wesley. All rights reserved. Chapter 5 Divide and Conquer Slides by Kevin Wayne. Copyright 25 Pearson-Addison Wesley. All rights reserved. Divide-and-Conquer Divide-and-conquer. Break up problem into several parts. Solve each part

More information

Lecture 4 CS781 February 3, 2011

Lecture 4 CS781 February 3, 2011 Lecture 4 CS78 February 3, 2 Topics: Data Compression-Huffman Trees Divide-and-Conquer Solving Recurrence Relations Counting Inversions Closest Pair Integer Multiplication Matrix Multiplication Data Compression

More information

CSE 202 Divide-and-conquer algorithms. Fan Chung Graham UC San Diego

CSE 202 Divide-and-conquer algorithms. Fan Chung Graham UC San Diego CSE 22 Divide-and-conquer algorithms Fan Chung Graham UC San Diego Announcements Homework due today before the class. About homework, write your own homework, allowing oral discussion with one fixed partner.

More information

CSE 202 Divide-and-conquer algorithms. Fan Chung Graham UC San Diego

CSE 202 Divide-and-conquer algorithms. Fan Chung Graham UC San Diego CSE 22 Divide-and-conquer algorithms Fan Chung Graham UC San Diego A useful fact about trees Any tree on n vertices contains a vertex v whose removal separates the remaining graph into two parts, one of

More information

Divide-and-Conquer. Combine solutions to sub-problems into overall solution. Break up problem of size n into two equal parts of size!n.

Divide-and-Conquer. Combine solutions to sub-problems into overall solution. Break up problem of size n into two equal parts of size!n. Chapter 5 Divide and Conquer Slides by Kevin Wayne. Copyright 25 Pearson-Addon Wesley. All rights reserved. Divide-and-Conquer Divide-and-conquer. Break up problem into several parts. Solve each part recursively.

More information

Advanced Algorithms. Problem solving Techniques. Divide and Conquer הפרד ומשול

Advanced Algorithms. Problem solving Techniques. Divide and Conquer הפרד ומשול Advanced Algorithms Problem solving Techniques. Divide and Conquer הפרד ומשול 1 Divide and Conquer A method of designing algorithms that (informally) proceeds as follows: Given an instance of the problem

More information

Chapter 3:- Divide and Conquer. Compiled By:- Sanjay Patel Assistant Professor, SVBIT.

Chapter 3:- Divide and Conquer. Compiled By:- Sanjay Patel Assistant Professor, SVBIT. Chapter 3:- Divide and Conquer Compiled By:- Assistant Professor, SVBIT. Outline Introduction Multiplying large Integers Problem Problem Solving using divide and conquer algorithm - Binary Search Sorting

More information

IS 709/809: Computational Methods in IS Research. Algorithm Analysis (Sorting)

IS 709/809: Computational Methods in IS Research. Algorithm Analysis (Sorting) IS 709/809: Computational Methods in IS Research Algorithm Analysis (Sorting) Nirmalya Roy Department of Information Systems University of Maryland Baltimore County www.umbc.edu Sorting Problem Given an

More information

Mergesort again. 1. Split the list into two equal parts

Mergesort again. 1. Split the list into two equal parts Quicksort Mergesort again 1. Split the list into two equal parts 5 3 9 2 8 7 3 2 1 4 5 3 9 2 8 7 3 2 1 4 Mergesort again 2. Recursively mergesort the two parts 5 3 9 2 8 7 3 2 1 4 2 3 5 8 9 1 2 3 4 7 Mergesort

More information

Sorting. Bubble Sort. Pseudo Code for Bubble Sorting: Sorting is ordering a list of elements.

Sorting. Bubble Sort. Pseudo Code for Bubble Sorting: Sorting is ordering a list of elements. Sorting Sorting is ordering a list of elements. Types of sorting: There are many types of algorithms exist based on the following criteria: Based on Complexity Based on Memory usage (Internal & External

More information

Design and Analysis of Algorithms

Design and Analysis of Algorithms Design and Analysis of Algorithms CSE 5311 Lecture 8 Sorting in Linear Time Junzhou Huang, Ph.D. Department of Computer Science and Engineering CSE5311 Design and Analysis of Algorithms 1 Sorting So Far

More information

Problem. Input: An array A = (A[1],..., A[n]) with length n. Output: a permutation A of A, that is sorted: A [i] A [j] for all. 1 i j n.

Problem. Input: An array A = (A[1],..., A[n]) with length n. Output: a permutation A of A, that is sorted: A [i] A [j] for all. 1 i j n. Problem 5. Sorting Simple Sorting, Quicksort, Mergesort Input: An array A = (A[1],..., A[n]) with length n. Output: a permutation A of A, that is sorted: A [i] A [j] for all 1 i j n. 98 99 Selection Sort

More information

Unit-2 Divide and conquer 2016

Unit-2 Divide and conquer 2016 2 Divide and conquer Overview, Structure of divide-and-conquer algorithms, binary search, quick sort, Strassen multiplication. 13% 05 Divide-and- conquer The Divide and Conquer Paradigm, is a method of

More information

Quicksort (Weiss chapter 8.6)

Quicksort (Weiss chapter 8.6) Quicksort (Weiss chapter 8.6) Recap of before Easter We saw a load of sorting algorithms, including mergesort To mergesort a list: Split the list into two halves Recursively mergesort the two halves Merge

More information

Sorting. Sorting. Stable Sorting. In-place Sort. Bubble Sort. Bubble Sort. Selection (Tournament) Heapsort (Smoothsort) Mergesort Quicksort Bogosort

Sorting. Sorting. Stable Sorting. In-place Sort. Bubble Sort. Bubble Sort. Selection (Tournament) Heapsort (Smoothsort) Mergesort Quicksort Bogosort Principles of Imperative Computation V. Adamchik CS 15-1 Lecture Carnegie Mellon University Sorting Sorting Sorting is ordering a list of objects. comparison non-comparison Hoare Knuth Bubble (Shell, Gnome)

More information

CS 310 Advanced Data Structures and Algorithms

CS 310 Advanced Data Structures and Algorithms CS 310 Advanced Data Structures and Algorithms Sorting June 13, 2017 Tong Wang UMass Boston CS 310 June 13, 2017 1 / 42 Sorting One of the most fundamental problems in CS Input: a series of elements with

More information

Divide-and-Conquer. Dr. Yingwu Zhu

Divide-and-Conquer. Dr. Yingwu Zhu Divide-and-Conquer Dr. Yingwu Zhu Divide-and-Conquer The most-well known algorithm design technique: 1. Divide instance of problem into two or more smaller instances 2. Solve smaller instances independently

More information

Lecture 9: Sorting Algorithms

Lecture 9: Sorting Algorithms Lecture 9: Sorting Algorithms Bo Tang @ SUSTech, Spring 2018 Sorting problem Sorting Problem Input: an array A[1..n] with n integers Output: a sorted array A (in ascending order) Problem is: sort A[1..n]

More information

Fast Sorting and Selection. A Lower Bound for Worst Case

Fast Sorting and Selection. A Lower Bound for Worst Case Lists and Iterators 0//06 Presentation for use with the textbook, Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 0 Fast Sorting and Selection USGS NEIC. Public domain government

More information

DIVIDE AND CONQUER ALGORITHMS ANALYSIS WITH RECURRENCE EQUATIONS

DIVIDE AND CONQUER ALGORITHMS ANALYSIS WITH RECURRENCE EQUATIONS CHAPTER 11 SORTING ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN C++, GOODRICH, TAMASSIA AND MOUNT (WILEY 2004) AND SLIDES FROM NANCY M. AMATO AND

More information

Divide and Conquer Sorting Algorithms and Noncomparison-based

Divide and Conquer Sorting Algorithms and Noncomparison-based Divide and Conquer Sorting Algorithms and Noncomparison-based Sorting Algorithms COMP1927 16x1 Sedgewick Chapters 7 and 8 Sedgewick Chapter 6.10, Chapter 10 DIVIDE AND CONQUER SORTING ALGORITHMS Step 1

More information

Divide and Conquer Algorithms: Advanced Sorting. Prichard Ch. 10.2: Advanced Sorting Algorithms

Divide and Conquer Algorithms: Advanced Sorting. Prichard Ch. 10.2: Advanced Sorting Algorithms Divide and Conquer Algorithms: Advanced Sorting Prichard Ch. 10.2: Advanced Sorting Algorithms 1 Sorting Algorithm n Organize a collection of data into either ascending or descending order. n Internal

More information

CS S-11 Sorting in Θ(nlgn) 1. Base Case: A list of length 1 or length 0 is already sorted. Recursive Case:

CS S-11 Sorting in Θ(nlgn) 1. Base Case: A list of length 1 or length 0 is already sorted. Recursive Case: CS245-2015S-11 Sorting in Θ(nlgn) 1 11-0: Merge Sort Recursive Sorting Base Case: A list of length 1 or length 0 is already sorted Recursive Case: Split the list in half Recursively sort two halves Merge

More information

Chapter 4. Divide-and-Conquer. Copyright 2007 Pearson Addison-Wesley. All rights reserved.

Chapter 4. Divide-and-Conquer. Copyright 2007 Pearson Addison-Wesley. All rights reserved. Chapter 4 Divide-and-Conquer Copyright 2007 Pearson Addison-Wesley. All rights reserved. Divide-and-Conquer The most-well known algorithm design strategy: 2. Divide instance of problem into two or more

More information

7. Sorting I. 7.1 Simple Sorting. Problem. Algorithm: IsSorted(A) 1 i j n. Simple Sorting

7. Sorting I. 7.1 Simple Sorting. Problem. Algorithm: IsSorted(A) 1 i j n. Simple Sorting Simple Sorting 7. Sorting I 7.1 Simple Sorting Selection Sort, Insertion Sort, Bubblesort [Ottman/Widmayer, Kap. 2.1, Cormen et al, Kap. 2.1, 2.2, Exercise 2.2-2, Problem 2-2 19 197 Problem Algorithm:

More information

Algorithms and Data Structures (INF1) Lecture 7/15 Hua Lu

Algorithms and Data Structures (INF1) Lecture 7/15 Hua Lu Algorithms and Data Structures (INF1) Lecture 7/15 Hua Lu Department of Computer Science Aalborg University Fall 2007 This Lecture Merge sort Quick sort Radix sort Summary We will see more complex techniques

More information

Divide and Conquer CISC4080, Computer Algorithms CIS, Fordham Univ. Instructor: X. Zhang

Divide and Conquer CISC4080, Computer Algorithms CIS, Fordham Univ. Instructor: X. Zhang Divide and Conquer CISC4080, Computer Algorithms CIS, Fordham Univ. Instructor: X. Zhang Acknowledgement The set of slides have use materials from the following resources Slides for textbook by Dr. Y.

More information

Searching, Sorting. part 1

Searching, Sorting. part 1 Searching, Sorting part 1 Week 3 Objectives Searching: binary search Comparison-based search: running time bound Sorting: bubble, selection, insertion, merge Sorting: Heapsort Comparison-based sorting

More information

Divide and Conquer CISC4080, Computer Algorithms CIS, Fordham Univ. Acknowledgement. Outline

Divide and Conquer CISC4080, Computer Algorithms CIS, Fordham Univ. Acknowledgement. Outline Divide and Conquer CISC4080, Computer Algorithms CIS, Fordham Univ. Instructor: X. Zhang Acknowledgement The set of slides have use materials from the following resources Slides for textbook by Dr. Y.

More information

COMP Data Structures

COMP Data Structures COMP 2140 - Data Structures Shahin Kamali Topic 5 - Sorting University of Manitoba Based on notes by S. Durocher. COMP 2140 - Data Structures 1 / 55 Overview Review: Insertion Sort Merge Sort Quicksort

More information

CSC Design and Analysis of Algorithms

CSC Design and Analysis of Algorithms CSC 8301- Design and Analysis of Algorithms Lecture 6 Divide and Conquer Algorithm Design Technique Divide-and-Conquer The most-well known algorithm design strategy: 1. Divide a problem instance into two

More information

CHAPTER 7 Iris Hui-Ru Jiang Fall 2008

CHAPTER 7 Iris Hui-Ru Jiang Fall 2008 CHAPTER 7 SORTING Iris Hui-Ru Jiang Fall 2008 2 Contents Comparison sort Bubble sort Selection sort Insertion sort Merge sort Quick sort Heap sort Introspective sort (Introsort) Readings Chapter 7 The

More information

Data Structures and Algorithms

Data Structures and Algorithms Data Structures and Algorithms Session 24. Earth Day, 2009 Instructor: Bert Huang http://www.cs.columbia.edu/~bert/courses/3137 Announcements Homework 6 due before last class: May 4th Final Review May

More information

CSC Design and Analysis of Algorithms. Lecture 6. Divide and Conquer Algorithm Design Technique. Divide-and-Conquer

CSC Design and Analysis of Algorithms. Lecture 6. Divide and Conquer Algorithm Design Technique. Divide-and-Conquer CSC 8301- Design and Analysis of Algorithms Lecture 6 Divide and Conquer Algorithm Design Technique Divide-and-Conquer The most-well known algorithm design strategy: 1. Divide a problem instance into two

More information

SORTING, SETS, AND SELECTION

SORTING, SETS, AND SELECTION CHAPTER 11 SORTING, SETS, AND SELECTION ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN C++, GOODRICH, TAMASSIA AND MOUNT (WILEY 2004) AND SLIDES FROM

More information

4. Sorting and Order-Statistics

4. Sorting and Order-Statistics 4. Sorting and Order-Statistics 4. Sorting and Order-Statistics The sorting problem consists in the following : Input : a sequence of n elements (a 1, a 2,..., a n ). Output : a permutation (a 1, a 2,...,

More information

CSE373: Data Structure & Algorithms Lecture 21: More Comparison Sorting. Aaron Bauer Winter 2014

CSE373: Data Structure & Algorithms Lecture 21: More Comparison Sorting. Aaron Bauer Winter 2014 CSE373: Data Structure & Algorithms Lecture 21: More Comparison Sorting Aaron Bauer Winter 2014 The main problem, stated carefully For now, assume we have n comparable elements in an array and we want

More information

CSE 373 MAY 24 TH ANALYSIS AND NON- COMPARISON SORTING

CSE 373 MAY 24 TH ANALYSIS AND NON- COMPARISON SORTING CSE 373 MAY 24 TH ANALYSIS AND NON- COMPARISON SORTING ASSORTED MINUTIAE HW6 Out Due next Wednesday ASSORTED MINUTIAE HW6 Out Due next Wednesday Only two late days allowed ASSORTED MINUTIAE HW6 Out Due

More information

Cpt S 122 Data Structures. Sorting

Cpt S 122 Data Structures. Sorting Cpt S 122 Data Structures Sorting Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Sorting Process of re-arranging data in ascending or descending order Given

More information

SORTING AND SELECTION

SORTING AND SELECTION 2 < > 1 4 8 6 = 9 CHAPTER 12 SORTING AND SELECTION ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016)

More information

Sorting. Bringing Order to the World

Sorting. Bringing Order to the World Lecture 10 Sorting Bringing Order to the World Lecture Outline Iterative sorting algorithms (comparison based) Selection Sort Bubble Sort Insertion Sort Recursive sorting algorithms (comparison based)

More information

The complexity of Sorting and sorting in linear-time. Median and Order Statistics. Chapter 8 and Chapter 9

The complexity of Sorting and sorting in linear-time. Median and Order Statistics. Chapter 8 and Chapter 9 Subject 6 Spring 2017 The complexity of Sorting and sorting in linear-time Median and Order Statistics Chapter 8 and Chapter 9 Disclaimer: These abbreviated notes DO NOT substitute the textbook for this

More information

Module 3: Sorting and Randomized Algorithms

Module 3: Sorting and Randomized Algorithms Module 3: Sorting and Randomized Algorithms CS 240 - Data Structures and Data Management Reza Dorrigiv, Daniel Roche School of Computer Science, University of Waterloo Winter 2010 Reza Dorrigiv, Daniel

More information

We can use a max-heap to sort data.

We can use a max-heap to sort data. Sorting 7B N log N Sorts 1 Heap Sort We can use a max-heap to sort data. Convert an array to a max-heap. Remove the root from the heap and store it in its proper position in the same array. Repeat until

More information

COT 5407: Introduction to Algorithms. Giri Narasimhan. ECS 254A; Phone: x3748

COT 5407: Introduction to Algorithms. Giri Narasimhan. ECS 254A; Phone: x3748 COT 5407: Introduction to Algorithms Giri Narasimhan ECS 254A; Phone: x3748 giri@cis.fiu.edu http://www.cis.fiu.edu/~giri/teach/5407s17.html https://moodle.cis.fiu.edu/v3.1/course/view.php?id=1494 1/19/17

More information

Sorting Algorithms. + Analysis of the Sorting Algorithms

Sorting Algorithms. + Analysis of the Sorting Algorithms Sorting Algorithms + Analysis of the Sorting Algorithms Insertion Sort What if first k elements of array are already sorted? 4, 7, 12, 5, 19, 16 We can shift the tail of the sorted elements list down and

More information

CS2223: Algorithms Sorting Algorithms, Heap Sort, Linear-time sort, Median and Order Statistics

CS2223: Algorithms Sorting Algorithms, Heap Sort, Linear-time sort, Median and Order Statistics CS2223: Algorithms Sorting Algorithms, Heap Sort, Linear-time sort, Median and Order Statistics 1 Sorting 1.1 Problem Statement You are given a sequence of n numbers < a 1, a 2,..., a n >. You need to

More information

DIVIDE & CONQUER. Problem of size n. Solution to sub problem 1

DIVIDE & CONQUER. Problem of size n. Solution to sub problem 1 DIVIDE & CONQUER Definition: Divide & conquer is a general algorithm design strategy with a general plan as follows: 1. DIVIDE: A problem s instance is divided into several smaller instances of the same

More information

Module 3: Sorting and Randomized Algorithms

Module 3: Sorting and Randomized Algorithms Module 3: Sorting and Randomized Algorithms CS 240 - Data Structures and Data Management Sajed Haque Veronika Irvine Taylor Smith Based on lecture notes by many previous cs240 instructors David R. Cheriton

More information

Module 3: Sorting and Randomized Algorithms. Selection vs. Sorting. Crucial Subroutines. CS Data Structures and Data Management

Module 3: Sorting and Randomized Algorithms. Selection vs. Sorting. Crucial Subroutines. CS Data Structures and Data Management Module 3: Sorting and Randomized Algorithms CS 240 - Data Structures and Data Management Sajed Haque Veronika Irvine Taylor Smith Based on lecture notes by many previous cs240 instructors David R. Cheriton

More information

Introduction to Computers and Programming. Today

Introduction to Computers and Programming. Today Introduction to Computers and Programming Prof. I. K. Lundqvist Lecture 10 April 8 2004 Today How to determine Big-O Compare data structures and algorithms Sorting algorithms 2 How to determine Big-O Partition

More information

Divide-and-Conquer. The most-well known algorithm design strategy: smaller instances. combining these solutions

Divide-and-Conquer. The most-well known algorithm design strategy: smaller instances. combining these solutions Divide-and-Conquer The most-well known algorithm design strategy: 1. Divide instance of problem into two or more smaller instances 2. Solve smaller instances recursively 3. Obtain solution to original

More information

Sorting and Selection

Sorting and Selection Sorting and Selection Introduction Divide and Conquer Merge-Sort Quick-Sort Radix-Sort Bucket-Sort 10-1 Introduction Assuming we have a sequence S storing a list of keyelement entries. The key of the element

More information

Algorithms and Applications

Algorithms and Applications Algorithms and Applications 1 Areas done in textbook: Sorting Algorithms Numerical Algorithms Image Processing Searching and Optimization 2 Chapter 10 Sorting Algorithms - rearranging a list of numbers

More information

Sorting. Sorting in Arrays. SelectionSort. SelectionSort. Binary search works great, but how do we create a sorted array in the first place?

Sorting. Sorting in Arrays. SelectionSort. SelectionSort. Binary search works great, but how do we create a sorted array in the first place? Sorting Binary search works great, but how do we create a sorted array in the first place? Sorting in Arrays Sorting algorithms: Selection sort: O(n 2 ) time Merge sort: O(nlog 2 (n)) time Quicksort: O(n

More information

Sorting Algorithms. For special input, O(n) sorting is possible. Between O(n 2 ) and O(nlogn) E.g., input integer between O(n) and O(n)

Sorting Algorithms. For special input, O(n) sorting is possible. Between O(n 2 ) and O(nlogn) E.g., input integer between O(n) and O(n) Sorting Sorting Algorithms Between O(n ) and O(nlogn) For special input, O(n) sorting is possible E.g., input integer between O(n) and O(n) Selection Sort For each loop Find max Swap max and rightmost

More information

Jana Kosecka. Linear Time Sorting, Median, Order Statistics. Many slides here are based on E. Demaine, D. Luebke slides

Jana Kosecka. Linear Time Sorting, Median, Order Statistics. Many slides here are based on E. Demaine, D. Luebke slides Jana Kosecka Linear Time Sorting, Median, Order Statistics Many slides here are based on E. Demaine, D. Luebke slides Insertion sort: Easy to code Fast on small inputs (less than ~50 elements) Fast on

More information

II (Sorting and) Order Statistics

II (Sorting and) Order Statistics II (Sorting and) Order Statistics Heapsort Quicksort Sorting in Linear Time Medians and Order Statistics 8 Sorting in Linear Time The sorting algorithms introduced thus far are comparison sorts Any comparison

More information

CS240 Fall Mike Lam, Professor. Quick Sort

CS240 Fall Mike Lam, Professor. Quick Sort ??!!!!! CS240 Fall 2015 Mike Lam, Professor Quick Sort Merge Sort Merge sort Sort sublists (divide & conquer) Merge sorted sublists (combine) All the "hard work" is done after recursing Hard to do "in-place"

More information

7 Sorting Algorithms. 7.1 O n 2 sorting algorithms. 7.2 Shell sort. Reading: MAW 7.1 and 7.2. Insertion sort: Worst-case time: O n 2.

7 Sorting Algorithms. 7.1 O n 2 sorting algorithms. 7.2 Shell sort. Reading: MAW 7.1 and 7.2. Insertion sort: Worst-case time: O n 2. 7 Sorting Algorithms 7.1 O n 2 sorting algorithms Reading: MAW 7.1 and 7.2 Insertion sort: 1 4 3 2 1 3 4 2 Selection sort: 1 4 3 2 Bubble sort: 1 3 2 4 7.2 Shell sort Reading: MAW 7.4 Introduction: Shell

More information

CS 303 Design and Analysis of Algorithms

CS 303 Design and Analysis of Algorithms Mid-term CS 303 Design and Analysis of Algorithms Review For Midterm Dong Xu (Based on class note of David Luebke) 12:55-1:55pm, Friday, March 19 Close book Bring your calculator 30% of your final score

More information

Better sorting algorithms (Weiss chapter )

Better sorting algorithms (Weiss chapter ) Better sorting algorithms (Weiss chapter 8.5 8.6) Divide and conquer Very general name for a type of recursive algorithm You have a problem to solve. Split that problem into smaller subproblems Recursively

More information

Sorting. Riley Porter. CSE373: Data Structures & Algorithms 1

Sorting. Riley Porter. CSE373: Data Structures & Algorithms 1 Sorting Riley Porter 1 Introduction to Sorting Why study sorting? Good algorithm practice! Different sorting algorithms have different trade-offs No single best sort for all scenarios Knowing one way to

More information

Sorting. Popular algorithms: Many algorithms for sorting in parallel also exist.

Sorting. Popular algorithms: Many algorithms for sorting in parallel also exist. Sorting Popular algorithms: Selection sort* Insertion sort* Bubble sort* Quick sort* Comb-sort Shell-sort Heap sort* Merge sort* Counting-sort Radix-sort Bucket-sort Tim-sort Many algorithms for sorting

More information

Parallel Sorting Algorithms

Parallel Sorting Algorithms CSC 391/691: GPU Programming Fall 015 Parallel Sorting Algorithms Copyright 015 Samuel S. Cho Sorting Algorithms Review Bubble Sort: O(n ) Insertion Sort: O(n ) Quick Sort: O(n log n) Heap Sort: O(n log

More information

Divide and Conquer Algorithms: Advanced Sorting

Divide and Conquer Algorithms: Advanced Sorting Divide and Conquer Algorithms: Advanced Sorting (revisit) Properties of Growth-rate functions(1/3) 1. You can ignore low-order terms in an algorithm's growth-rate function. O(n 3 +4n 2 +3n) it is also

More information

CS Divide and Conquer

CS Divide and Conquer CS483-07 Divide and Conquer Instructor: Fei Li Room 443 ST II Office hours: Tue. & Thur. 1:30pm - 2:30pm or by appointments lifei@cs.gmu.edu with subject: CS483 http://www.cs.gmu.edu/ lifei/teaching/cs483_fall07/

More information

SAMPLE OF THE STUDY MATERIAL PART OF CHAPTER 6. Sorting Algorithms

SAMPLE OF THE STUDY MATERIAL PART OF CHAPTER 6. Sorting Algorithms SAMPLE OF THE STUDY MATERIAL PART OF CHAPTER 6 6.0 Introduction Sorting algorithms used in computer science are often classified by: Computational complexity (worst, average and best behavior) of element

More information

Comparison Based Sorting Algorithms. Algorithms and Data Structures: Lower Bounds for Sorting. Comparison Based Sorting Algorithms

Comparison Based Sorting Algorithms. Algorithms and Data Structures: Lower Bounds for Sorting. Comparison Based Sorting Algorithms Comparison Based Sorting Algorithms Algorithms and Data Structures: Lower Bounds for Sorting Definition 1 A sorting algorithm is comparison based if comparisons A[i] < A[j], A[i] A[j], A[i] = A[j], A[i]

More information

Question 7.11 Show how heapsort processes the input:

Question 7.11 Show how heapsort processes the input: Question 7.11 Show how heapsort processes the input: 142, 543, 123, 65, 453, 879, 572, 434, 111, 242, 811, 102. Solution. Step 1 Build the heap. 1.1 Place all the data into a complete binary tree in the

More information

Sorting (I) Hwansoo Han

Sorting (I) Hwansoo Han Sorting (I) Hwansoo Han Sorting Algorithms Sorting for a short list Simple sort algorithms: O(n ) time Bubble sort, insertion sort, selection sort Popular sorting algorithm Quicksort: O(nlogn) time on

More information

Next. 1. Covered basics of a simple design technique (Divideand-conquer) 2. Next, more sorting algorithms.

Next. 1. Covered basics of a simple design technique (Divideand-conquer) 2. Next, more sorting algorithms. Next 1. Covered basics of a simple design technique (Divideand-conquer) Ch. 2 of the text. 2. Next, more sorting algorithms. Sorting Switch from design paradigms to applications. Sorting and order statistics

More information

CS473 - Algorithms I

CS473 - Algorithms I CS473 - Algorithms I Lecture 4 The Divide-and-Conquer Design Paradigm View in slide-show mode 1 Reminder: Merge Sort Input array A sort this half sort this half Divide Conquer merge two sorted halves Combine

More information

EECS 2011M: Fundamentals of Data Structures

EECS 2011M: Fundamentals of Data Structures M: Fundamentals of Data Structures Instructor: Suprakash Datta Office : LAS 3043 Course page: http://www.eecs.yorku.ca/course/2011m Also on Moodle Note: Some slides in this lecture are adopted from James

More information

How many leaves on the decision tree? There are n! leaves, because every permutation appears at least once.

How many leaves on the decision tree? There are n! leaves, because every permutation appears at least once. Chapter 8. Sorting in Linear Time Types of Sort Algorithms The only operation that may be used to gain order information about a sequence is comparison of pairs of elements. Quick Sort -- comparison-based

More information

Comparison Sorts. Chapter 9.4, 12.1, 12.2

Comparison Sorts. Chapter 9.4, 12.1, 12.2 Comparison Sorts Chapter 9.4, 12.1, 12.2 Sorting We have seen the advantage of sorted data representations for a number of applications Sparse vectors Maps Dictionaries Here we consider the problem of

More information

Lecture 5: Sorting Part A

Lecture 5: Sorting Part A Lecture 5: Sorting Part A Heapsort Running time O(n lg n), like merge sort Sorts in place (as insertion sort), only constant number of array elements are stored outside the input array at any time Combines

More information

08 A: Sorting III. CS1102S: Data Structures and Algorithms. Martin Henz. March 10, Generated on Tuesday 9 th March, 2010, 09:58

08 A: Sorting III. CS1102S: Data Structures and Algorithms. Martin Henz. March 10, Generated on Tuesday 9 th March, 2010, 09:58 08 A: Sorting III CS1102S: Data Structures and Algorithms Martin Henz March 10, 2010 Generated on Tuesday 9 th March, 2010, 09:58 CS1102S: Data Structures and Algorithms 08 A: Sorting III 1 1 Recap: Sorting

More information

Algorithms and Data Structures: Lower Bounds for Sorting. ADS: lect 7 slide 1

Algorithms and Data Structures: Lower Bounds for Sorting. ADS: lect 7 slide 1 Algorithms and Data Structures: Lower Bounds for Sorting ADS: lect 7 slide 1 ADS: lect 7 slide 2 Comparison Based Sorting Algorithms Definition 1 A sorting algorithm is comparison based if comparisons

More information

Introduction. e.g., the item could be an entire block of information about a student, while the search key might be only the student's name

Introduction. e.g., the item could be an entire block of information about a student, while the search key might be only the student's name Chapter 7 Sorting 2 Introduction sorting fundamental task in data management well-studied problem in computer science basic problem given an of items where each item contains a key, rearrange the items

More information

COT 6405 Introduction to Theory of Algorithms

COT 6405 Introduction to Theory of Algorithms COT 6405 Introduction to Theory of Algorithms Topic 10. Linear Time Sorting 10/5/2016 2 How fast can we sort? The sorting algorithms we learned so far Insertion Sort, Merge Sort, Heap Sort, and Quicksort

More information

Algorithmic Analysis. Go go Big O(h)!

Algorithmic Analysis. Go go Big O(h)! Algorithmic Analysis Go go Big O(h)! 1 Corresponding Book Sections Pearson: Chapter 6, Sections 1-3 Data Structures: 4.1-4.2.5 2 What is an Algorithm? Informally, any well defined computational procedure

More information

Can we do faster? What is the theoretical best we can do?

Can we do faster? What is the theoretical best we can do? Non-Comparison Based Sorting How fast can we sort? 2 Insertion-Sort O( n ) Merge-Sort, Quicksort (expected), Heapsort : ( n lg n ) Can we do faster? What is the theoretical best we can do? So far we have

More information

Sorting. Task Description. Selection Sort. Should we worry about speed?

Sorting. Task Description. Selection Sort. Should we worry about speed? Sorting Should we worry about speed? Task Description We have an array of n values in any order We need to have the array sorted in ascending or descending order of values 2 Selection Sort Select the smallest

More information

Sorting is ordering a list of objects. Here are some sorting algorithms

Sorting is ordering a list of objects. Here are some sorting algorithms Sorting Sorting is ordering a list of objects. Here are some sorting algorithms Bubble sort Insertion sort Selection sort Mergesort Question: What is the lower bound for all sorting algorithms? Algorithms

More information

Data Structures. Sorting. Haim Kaplan & Uri Zwick December 2013

Data Structures. Sorting. Haim Kaplan & Uri Zwick December 2013 Data Structures Sorting Haim Kaplan & Uri Zwick December 2013 1 Comparison based sorting key a 1 a 2 a n info Input: An array containing n items Keys belong to a totally ordered domain Two keys can be

More information

11/8/2016. Chapter 7 Sorting. Introduction. Introduction. Sorting Algorithms. Sorting. Sorting

11/8/2016. Chapter 7 Sorting. Introduction. Introduction. Sorting Algorithms. Sorting. Sorting Introduction Chapter 7 Sorting sorting fundamental task in data management well-studied problem in computer science basic problem given an array of items where each item contains a key, rearrange the items

More information

Sorting is a problem for which we can prove a non-trivial lower bound.

Sorting is a problem for which we can prove a non-trivial lower bound. Sorting The sorting problem is defined as follows: Sorting: Given a list a with n elements possessing a total order, return a list with the same elements in non-decreasing order. Remember that total order

More information

CS 561, Lecture 1. Jared Saia University of New Mexico

CS 561, Lecture 1. Jared Saia University of New Mexico CS 561, Lecture 1 Jared Saia University of New Mexico Quicksort Based on divide and conquer strategy Worst case is Θ(n 2 ) Expected running time is Θ(n log n) An In-place sorting algorithm Almost always

More information

Lecture 8: Mergesort / Quicksort Steven Skiena

Lecture 8: Mergesort / Quicksort Steven Skiena Lecture 8: Mergesort / Quicksort Steven Skiena Department of Computer Science State University of New York Stony Brook, NY 11794 4400 http://www.cs.stonybrook.edu/ skiena Problem of the Day Give an efficient

More information

CS 171: Introduction to Computer Science II. Quicksort

CS 171: Introduction to Computer Science II. Quicksort CS 171: Introduction to Computer Science II Quicksort Roadmap MergeSort Analysis of Recursive Algorithms QuickSort Algorithm Analysis Practical improvements Java Array.sort() methods Quick Sort Partition

More information

17/05/2018. Outline. Outline. Divide and Conquer. Control Abstraction for Divide &Conquer. Outline. Module 2: Divide and Conquer

17/05/2018. Outline. Outline. Divide and Conquer. Control Abstraction for Divide &Conquer. Outline. Module 2: Divide and Conquer Module 2: Divide and Conquer Divide and Conquer Control Abstraction for Divide &Conquer 1 Recurrence equation for Divide and Conquer: If the size of problem p is n and the sizes of the k sub problems are

More information

CS61BL. Lecture 5: Graphs Sorting

CS61BL. Lecture 5: Graphs Sorting CS61BL Lecture 5: Graphs Sorting Graphs Graphs Edge Vertex Graphs (Undirected) Graphs (Directed) Graphs (Multigraph) Graphs (Acyclic) Graphs (Cyclic) Graphs (Connected) Graphs (Disconnected) Graphs (Unweighted)

More information

CS 5321: Advanced Algorithms Sorting. Acknowledgement. Ali Ebnenasir Department of Computer Science Michigan Technological University

CS 5321: Advanced Algorithms Sorting. Acknowledgement. Ali Ebnenasir Department of Computer Science Michigan Technological University CS 5321: Advanced Algorithms Sorting Ali Ebnenasir Department of Computer Science Michigan Technological University Acknowledgement Eric Torng Moon Jung Chung Charles Ofria Nishit Chapter 22 Bill 23 Martin

More information

Test 1 Review Questions with Solutions

Test 1 Review Questions with Solutions CS3510 Design & Analysis of Algorithms Section A Test 1 Review Questions with Solutions Instructor: Richard Peng Test 1 in class, Wednesday, Sep 13, 2017 Main Topics Asymptotic complexity: O, Ω, and Θ.

More information

Data structures. More sorting. Dr. Alex Gerdes DIT961 - VT 2018

Data structures. More sorting. Dr. Alex Gerdes DIT961 - VT 2018 Data structures More sorting Dr. Alex Gerdes DIT961 - VT 2018 Divide and conquer Very general name for a type of recursive algorithm You have a problem to solve: - Split that problem into smaller subproblems

More information

Sorting: Given a list A with n elements possessing a total order, return a list with the same elements in non-decreasing order.

Sorting: Given a list A with n elements possessing a total order, return a list with the same elements in non-decreasing order. Sorting The sorting problem is defined as follows: Sorting: Given a list A with n elements possessing a total order, return a list with the same elements in non-decreasing order. Remember that total order

More information

Mergesort again. 1. Split the list into two equal parts

Mergesort again. 1. Split the list into two equal parts Quicksort Mergesort again 1. Split the list into two equal parts 5 3 9 2 8 7 3 2 1 4 5 3 9 2 8 7 3 2 1 4 Mergesort again 2. Recursively mergesort the two parts 5 3 9 2 8 7 3 2 1 4 2 3 5 8 9 1 2 3 4 7 Mergesort

More information

Sorting. Divide-and-Conquer 1

Sorting. Divide-and-Conquer 1 Sorting Divide-and-Conquer 1 Divide-and-Conquer 7 2 9 4 2 4 7 9 7 2 2 7 9 4 4 9 7 7 2 2 9 9 4 4 Divide-and-Conquer 2 Divide-and-Conquer Divide-and conquer is a general algorithm design paradigm: Divide:

More information