Sorting and Algorithm Analysis

Size: px
Start display at page:

Download "Sorting and Algorithm Analysis"

Transcription

1 Unt 7 Sortng and Algorthm Analyss Computer Scence S-111 Harvard Unversty Davd G. Sullvan, Ph.D. Sortng an Array of Integers n-2 n-1 arr Ground rules: sort the values n ncreasng order sort n place, usng only a small amount of addtonal storage Termnology: poston: one of the memory locatons n the array element: one of the data tems stored n the array element : the element at poston Goal: mnmze the number of comparsons C and the number of moves M needed to sort the array. move = copyng an element from one poston to another example: arr[3] = arr[5];

2 Defnng a Class for our Sort Methods publc class Sort { publc statc vod bubblesort(nt[] arr) {... publc statc vod nsertonsort(nt[] arr) { Our Sort class s smply a collecton of methods lke Java s bult-n Math class. Because we never create Sort objects, all of the methods n the class must be statc. outsde the class, we nvoke them usng the class name: e.g., Sort.bubbleSort(arr) Defnng a Swap Method It would be helpful to have a method that swaps two elements of the array. Why won t the followng work? publc statc vod swap(nt a, nt b) { nt temp = a; a = b; b = temp;

3 An Incorrect Swap Method publc statc vod swap(nt a, nt b) { nt temp = a; a = b; b = temp; Trace through the followng lnes to see the problem: nt[] arr = {15, 7, ; swap(arr[0], arr[1]); stack heap arr Ths method works: A Correct Swap Method publc statc vod swap(nt[] arr, nt a, nt b) { nt temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; Trace through the followng wth a memory dagram to convnce yourself that t works: nt[] arr = {15, 7, ; swap(arr, 0, 1);

4 Selecton Sort Basc dea: consder the postons n the array from left to rght for each poston, fnd the element that belongs there and put t n place by swappng t wth the element that s currently there Example: Why don t we need to consder poston 4? Selectng an Element When we consder poston, the elements n postons 0 through 1are already n ther fnal postons example for =3: To select an element for poston : consder elements, +1,+2,,arr.length 1, and keep track of ndexmn, the ndex of the smallest element seen thus far ndexmn: 3, when we fnsh ths pass, ndexmn s the ndex of the element that belongs n poston. swap arr[] and arr[ndexmn]:

5 Implementaton of Selecton Sort Use a helper method to fnd the ndex of the smallest element: prvate statc nt ndexsmallest(nt[] arr, nt start) { nt ndexmn = start; for (nt = start + 1; < arr.length; ++) { f (arr[] < arr[ndexmn]) { ndexmn = ; return ndexmn; The actual sort method s very smple: publc statc vod selectonsort(nt[] arr) { for (nt = 0; < arr.length - 1; ++) { nt j = ndexsmallest(arr, ); swap(arr,, j); Tme Analyss Some algorthms are much more effcent than others. The tme effcency or tme complexty of an algorthm s some measure of the number of operatons that t performs. for sortng algorthms, we ll focus on two types of operatons: comparsons and moves The number of operatons that an algorthm performs typcally depends on the sze, n, of ts nput. for sortng algorthms, n s the # of elements n the array C(n) = number of comparsons M(n) = number of moves To express the tme complexty of an algorthm, we ll express the number of operatons performed as a functon of n. examples: C(n) = n 2 +3n M(n) = 2n 2-1

6 Countng Comparsons by Selecton Sort prvate statc nt ndexsmallest(nt[] arr, nt start){ nt ndexmn = start; for (nt = start + 1; < arr.length; ++) { f (arr[] < arr[ndexmn]) { ndexmn = ; return ndexmn; publc statc vod selectonsort(nt[] arr) { for (nt = 0; < arr.length - 1; ++) { nt j = ndexsmallest(arr, ); swap(arr,, j); To sort n elements, selecton sort performs n-1passes: on 1st pass, t performs comparsons to fnd ndexsmallest on 2nd pass, t performs comparsons on the (n-1)st pass, t performs 1 comparson Addng them up: C(n) = (n - 2) + (n - 1) Countng Comparsons by Selecton Sort (cont.) The resultng formula for C(n) s the sum of an arthmetc sequence: C(n) = (n - 2) + (n - 1) = Formula for the sum of ths type of arthmetc sequence: Thus, we can smplfy our expresson for C(n) as follows: C(n) = (n - 1)((n - 1) 1) = 2 = n m 1 (n - 1)n 2 m(m 1) 2 C(n) = n n n 2

7 Focusng on the Largest Term When n s large, mathematcal expressons of n are domnated by ther largest term.e., the term that grows fastest as a functon of n. example: n n 2 /2 n/2 n 2 /2 n/ ,000, ,995,000 In characterzng the tme complexty of an algorthm, we ll focus on the largest term n ts operaton-count expresson. for selecton sort, C(n) = n 2 /2 - n/2 n 2 /2 In addton, we ll typcally gnore the coeffcent of the largest term (e.g., n 2 /2 n 2 ). Bg-O Notaton We specfy the largest term usng bg-o notaton. e.g., we say that C(n) = n 2 /2 n/2 s O(n 2 ) Common classes of algorthms: name example expressons bg-o notaton constant tme 1, 7, 10 O(1) logarthmc tme 3log 10 n, log 2 n+5 O(log n) lnear tme 5n, 10n 2log 2 n O(n) nlogn tme 4nlog 2 n, nlog 2 n+n O(nlog n) quadratc tme 2n 2 + 3n, n 2 1 O(n 2 ) exponental tme 2 n, 5e n +2n 2 O(c n ) slower For large nputs, effcency matters more than CPU speed. e.g., an O(log n) algorthm on a slow machne wll outperform an O(n) algorthm on a fast machne

8 Orderng of Functons We can see below that: n 2 grows faster than nlog 2 n nlog 2 n grows faster than n n grows faster than log 2 n n^2 n log n n log n n Orderng of Functons (cont.) Zoomng n, we see that: n 2 >= n for all n >= 1 nlog 2 n >= n for all n >= 2 n > log 2 n for all n >= n^2 n log n n log n

9 Bg-O Tme Analyss of Selecton Sort Comparsons: we showed that C(n) = n 2 /2 n/2 selecton sort performs O(n 2 ) comparsons Moves: after each of the n-1 passes, the algorthm does one swap. n 1 swaps, 3 moves per swap M(n) = 3(n-1) = 3n-3 selecton sort performs O(n) moves. Runnng tme (.e., total operatons):? Mathematcal Defnton of Bg-O Notaton f(n) = O(g(n)) f there exst postve constants c and n 0 such that f(n) <= cg(n) for all n >= n 0 Example: f(n) = n 2 /2 n/2 s O(n 2 ), because n 2 /2 n/2 <= n 2 for all n >= 0. c = 1 n 0 = 0 g(n) = n 2 f(n) = n 2 /2 n/2 n Bg-O notaton specfes an upper bound on a functon f(n) as n grows large.

10 Bg-O Notaton and Tght Bounds Bg-O notaton provdes an upper bound, not a tght bound (upper and lower). Example: 3n 3 s O(n 2 ) because 3n 3 <= n 2 for all n >= 1 3n 3 s also O(2 n ) because 3n 3 <= 2 n for all n >= 1 However, we generally try to use bg-o notaton to characterze a functon as closely as possble.e., as f we were usng t to specfy a tght bound. for our example, we would say that 3n 3 s O(n) Bg-Theta Notaton In theoretcal computer scence, bg-theta notaton ( ) s used to specfy a tght bound. f(n) = (g(n)) f there exst constants c 1, c 2, and n 0 such that c 1 g(n) <= f(n) <= c 2 g(n) for all n > n 0 Example: f(n) = n 2 /2 n/2 s (n 2 ), because (1/4)*n 2 <= n 2 /2 n/2 <= n 2 for all n >= 2 c 1 = 1/4 c 2 = 1 n 0 = 2 g(n) = n 2 f(n) = n 2 /2 n/2 n (1/4) * g(n) = n 2 /4

11 Sortng by Inserton I: Inserton Sort Basc dea: gong from left to rght, nsert each element nto ts proper place wth respect to the elements to ts left, sldng over other elements to make room. Example: Comparng Selecton and Inserton Strateges In selecton sort, we start wth the postons n the array and select the correct elements to fll them. In nserton sort, we start wth the elements and determne where to nsert them n the array. Here s an example that llustrates the dfference: Sortng by selecton: consder poston 0: fnd the element (2) that belongs there consder poston 1: fnd the element (9) that belongs there Sortng by nserton: consder the 12: determne where to nsert t consder the 15; determne where to nsert t

12 Insertng an Element When we consder element, elements 0 through 1 are already sorted wth respect to each other. example for =3: To nsert element : make a copy of element, storng t n the varable toinsert: toinsert consder elements -1, -2, f an element > toinsert, slde t over to the rght stop at the frst element <= toinsert toinsert 19 copy toinsert nto the resultng hole : Inserton Sort Example (done together) descrpton of steps

13 Implementaton of Inserton Sort publc class Sort {... publc statc vod nsertonsort(nt[] arr) { for (nt = 1; < arr.length; ++) { f (arr[] < arr[-1]) { nt toinsert = arr[]; nt j = ; do { arr[j] = arr[j-1]; j = j - 1; whle (j > 0 && toinsert < arr[j-1]); arr[j] = toinsert; Tme Analyss of Inserton Sort The number of operatons depends on the contents of the array. best case: array s sorted thus, we never execute the do-whle loop each element s only compared to the element to ts left C(n) = n 1 = O(n), M(n) = 0, runnng tme = O(n) worst case: array s n reverse order each element s compared to all of the elements to ts left: arr[1] s compared to 1 element (arr[0]) arr[2] s compared to 2 elements (arr[0] and arr[1]) arr[n-1] s compared to n-1 elements C(n) = (n 1)=O(n 2 ) as seen n selecton sort smlarly, M(n) = O(n 2 ), runnng tme = O(n 2 ) average case:

14 Sortng by Inserton II: Shell Sort Developed by Donald Shell n 1959 Improves on nserton sort Takes advantage of the fact that nserton sort s fast when an array s almost sorted. Seeks to elmnate a dsadvantage of nserton sort: f an element s far from ts fnal locaton, many small moves are requred to put t where t belongs. Example: f the largest element starts out at the begnnng of the array, t moves one place to the rght on every nserton! Shell sort uses larger moves that allow elements to quckly get close to where they belong. Sortng Subarrays Basc dea: use nserton sort on subarrays that contan elements separated by some ncrement ncrements allow the data tems to make larger jumps repeat usng a decreasng sequence of ncrements Example for an ntal ncrement of 3: three subarrays: 1) elements 0, 3, 6 2) elements 1, 4, 7 3) elements 2 and 5 Sort the subarrays usng nserton sort to get the followng: Next, we complete the process usng an ncrement of 1.

15 Shell Sort: A Sngle Pass We don t consder the subarrays one at a tme. We consder elements arr[ncr] through arr[arr.length-1], nsertng each element nto ts proper place wth respect to the elements from ts subarray that are to the left of the element. The same example (ncr = 3): When we consder element, the other elements n ts subarray are already sorted wth respect to each other. example for =6: (ncr = 3) the other element s n 9 s subarray (the 27 and 36) are already sorted wth respect to each other To nsert element : make a copy of element, storng t n the varable toinsert: toinsert Insertng an Element n a Subarray 9 consder elements -ncr, -(2*ncr), -(3*ncr), f an element > toinsert, slde t rght wthn the subarray stop at the frst element <= toinsert copy toinsert nto the hole : toinsert

16 The Sequence of Increments Dfferent sequences of decreasng ncrements can be used. Our verson uses values that are one less than a power of two. 2 k 1 for some k 63, 31, 15, 7, 3, 1 can get to the next lower ncrement usng nteger dvson: ncr = ncr/2; Should avod numbers that are multples of each other. otherwse, elements that are sorted wth respect to each other n one pass are grouped together agan n subsequent passes repeat comparsons unnecessarly get fewer of the large jumps that speed up later passes example of a bad sequence: 64, 32, 16, 8, 4, 2, 1 what happens f the largest values are all n odd postons? Implementaton of Shell Sort publc statc vod shellsort(nt[] arr) { nt ncr = 1; whle (2 * ncr <= arr.length) { ncr = 2 * ncr; ncr = ncr - 1; whle (ncr >= 1) { for (nt = ncr; < arr.length; ++) { f (arr[] < arr[-ncr]) { nt toinsert = arr[]; nt j = ; do { arr[j] = arr[j-ncr]; j = j - ncr; whle (j > ncr-1 && toinsert < arr[j-ncr]); arr[j] = toinsert; ncr = ncr/2; (If you replace ncr wth 1 n the for-loop, you get the code for nserton sort.)

17 Tme Analyss of Shell Sort Dffcult to analyze precsely typcally use experments to measure ts effcency Wth a bad nterval sequence, t s O(n 2 ) n the worst case. Wth a good nterval sequence, t s better than O(n 2 ). at least O(n 1.5 ) n the average and worst case some experments have shown average-case runnng tmes of O(n 1.25 ) or even O(n 7/6 ) Sgnfcantly better than nserton or selecton for large n: n n 2 n 1.5 n , , ,000,000 1,000, , x 10 7 We ve wrapped nserton sort n another loop and ncreased ts effcency! The key s n the larger jumps that Shell sort allows. Practcng Tme Analyss Consder the followng statc method: publc statc nt mystery(nt n) { nt x = 0; for (nt = 0; < n; ++) { x += ; // statement 1 for (nt j = 0; j < ; j++) { x += j; return x; What s the bg-o expresson for the number of tmes that statement 1 s executed as a functon of the nput n?

18 What about now? Consder the followng statc method: publc statc nt mystery(nt n) { nt x = 0; for (nt = 0; < 3*n + 4; ++) { x += ; // statement 1 for (nt j = 0; j < ; j++) { x += j; return x; What s the bg-o expresson for the number of tmes that statement 1 s executed as a functon of the nput n? Practcng Tme Analyss Consder the followng statc method: publc statc nt mystery(nt n) { nt x = 0; for (nt = 0; < n; ++) { x += ; // statement 1 for (nt j = 0; j < ; j++) { x += j; // statement 2 return x; What s the bg-o expresson for the number of tmes that statement 2 s executed as a functon of the nput n? value of number of tmes statement 2 s executed

19 Sortng by Exchange I: Bubble Sort Perform a sequence of passes through the array. On each pass: proceed from left to rght, swappng adjacent elements f they are out of order. Larger elements bubble up to the end of the array. At the end of the kth pass, the k rghtmost elements are n ther fnal postons, so we don t need to consder them n subsequent passes Example: after the frst pass: after the second: after the thrd: Implementaton of Bubble Sort publc class Sort {... publc statc vod bubblesort(nt[] arr) { for (nt = arr.length 1; > 0; --) { for (nt j = 0; j < ; j++) { f (arr[j] > arr[j+1]) { swap(arr, j, j+1); One for-loop nested n another: the nner loop performs a sngle pass the outer loop governs the number of passes, and the endng pont of each pass

20 Tme Analyss of Bubble Sort Comparsons: the kth pass performs comparsons, so we get C(n) = Moves: depends on the contents of the array n the worst case: n the best case: Runnng tme: Sortng by Exchange II: Qucksort Lke bubble sort, qucksort uses an approach based on exchangng out-of-order elements, but t s more effcent. A recursve, dvde-and-conquer algorthm: dvde: rearrange the elements so that we end up wth two subarrays that meet the followng crteron: each element n the left array <= each element n the rght array example: conquer: apply qucksort recursvely to the subarrays, stoppng when a subarray has a sngle element combne: nothng needs to be done, because of the crteron used n formng the subarrays

21 Parttonng an Array Usng a Pvot The process that qucksort uses to rearrange the elements s known as parttonng the array. Parttonng s done usng a value known as the pvot. We rearrange the elements to produce two subarrays: left subarray: all values <= pvot rght subarray: all values >= pvot partton usng a pvot of all values <= 9 all values >= 9 equvalent to the crteron on the prevous page. Our approach to parttonng s one of several varants. Parttonng s useful n ts own rght. ex: fnd all students wth a GPA > 3.0. Possble Pvot Values Frst element or last element rsky, can lead to terrble worst-case behavor especally poor f the array s almost sorted pvot = 18 Mddle element (what we wll use) Randomly chosen element Medan of three elements left, center, and rght elements three randomly selected elements takng the medan of three decreases the probablty of gettng a poor pvot

22 arr Parttonng an Array: An Example Mantan ndces and j, startng them outsde the array: = frst 1 j = last + 1 frst pvot = 9 last j Fnd out of place elements: ncrement untl arr[] >= pvot decrement j untl arr[j] <= pvot Swap arr[] and arr[j]: j j Parttonng Example (cont.) j from prev. page: Fnd: Swap: j j Fnd: j and now the ndces have crossed, so we return j. Subarrays: left = arr[frst : j], rght = arr[j+1 : last] frst j last

23 Parttonng Example 2 Start (pvot = 13): j j Fnd: Swap: j Fnd: j and now the ndces are equal, so we return j. Subarrays: j Parttonng Example 3 (done together) Start (pvot = 5): j Fnd:

24 Start (pvot = 15): Parttonng Example j Fnd: partton() Helper Method prvate statc nt partton(nt[] arr, nt frst, nt last) { nt pvot = arr[(frst + last)/2]; nt = frst - 1; // ndex gong left to rght nt j = last + 1; // ndex gong rght to left whle (true) { do { ++; whle (arr[] < pvot); do { j--; whle (arr[j] > pvot); f ( < j) { swap(arr,, j); else { return j; // arr[j] = end of left array frst last

25 Implementaton of Qucksort publc statc vod qucksort(nt[] arr) { // "wrapper" method qsort(arr, 0, arr.length - 1); prvate statc vod qsort(nt[] arr, nt frst, nt last) { nt splt = partton(arr, frst, last); f (frst < splt) { // f left subarray has 2+ values qsort(arr, frst, splt); // sort t recursvely! f (last > splt + 1) { // f rght has 2+ values qsort(arr, splt + 1, last); // sort t! // note: base case s when nether call s made, // because both subarrays have only one element! frst splt (j) last A Quck Revew of Logarthms log b n = the exponent to whch b must be rased to get n log b n = p f b p = n examples: log 2 8 = 3 because 2 3 = 8 log = 4 because 10 4 = Another way of lookng at logs: let's say that you repeatedly dvde n by b (usng nteger dvson) log b n s an upper bound on the number of dvsons needed to reach 1 example: log 2 18 s approx /2 = 9 9/2 = 4 4/2 = 2 2/2 = 1

26 A Quck Revew of Logs (cont.) If the number of operatons performed by an algorthm s proportonal to log b n for any base b, we say t s a O(log n) algorthm droppng the base. log b n grows much more slowly than n n log 2 n (1K) *1024 (1M) 20 Thus, for large values of n: a O(log n) algorthm s much faster than a O(n) algorthm a O(nlogn) algorthm s much faster than a O(n 2 ) algorthm We can also show that an O(nlogn) algorthm s faster than a O(n 1.5 ) algorthm lke Shell sort. Tme Analyss of Qucksort Parttonng an array requres n comparsons, because each element s compared wth the pvot. best case: parttonng always dvdes the array n half repeated recursve calls gve: n/2 n/2 n/4 n/4 n/4 n/ n comparsons n 2*(n/2) = n 4*(n/4) = n... at each "row" except the bottom, we perform n comparsons there are rows that nclude comparsons C(n) =? Smlarly, M(n) and runnng tme are both 0

27 Tme Analyss of Qucksort (cont.) worst case: pvot s always the smallest or largest element one subarray has 1 element, the other has n - 1 repeated recursve calls gve: comparsons n n 1 n-1 n-1 1 n-2 n-2 1 n-3 n n 1 1 C(n) = = O(n 2 ). M(n) and run tme are also O(n 2 ). 2 average case s harder to analyze C(n) > n log 2 n, but t s stll O(n log n) Mergesort All of the comparson-based sortng algorthms that we've seen thus far have sorted the array n place. used only a small amount of addtonal memory Mergesort s a sortng algorthm that requres an addtonal temporary array of the same sze as the orgnal one. t needs O(n) addtonal space, where n s the array sze It s based on the process of mergng two sorted arrays nto a sngle sorted array. example:

28 Mergng Sorted Arrays To merge sorted arrays A and B nto an array C, we mantan three ndces, whch start out on the frst elements of the arrays: A k j C B We repeatedly do the followng: compare A[] and B[j] copy the smaller of the two to C[k] ncrement the ndex of the array whose element was coped ncrement k A k j C 2 B Mergng Sorted Arrays (cont.) Startng pont: A k j C B After the frst copy: A j B C 2 k After the second copy: A j B C 2 5 k

29 Mergng Sorted Arrays (cont.) After the thrd copy: A k j C B After the fourth copy: A j B C k After the ffth copy: A j B C k Mergng Sorted Arrays (cont.) After the sxth copy: A j C B k There's nothng left n B, so we smply copy the remanng elements from A: A j C B k

30 Dvde and Conquer Lke qucksort, mergesort s a dvde-and-conquer algorthm. dvde: splt the array n half, formng two subarrays conquer: apply mergesort recursvely to the subarrays, stoppng when a subarray has a sngle element combne: merge the sorted subarrays splt splt splt merge merge merge Tracng the Calls to Mergesort the ntal call s made to sort the entre array: splt nto two 4-element subarrays, and make a recursve call to sort the left subarray: splt nto two 2-element subarrays, and make a recursve call to sort the left subarray:

31 Tracng the Calls to Mergesort splt nto two 1-element subarrays, and make a recursve call to sort the left subarray: base case, so return to the call for the subarray {12, 8: Tracng the Calls to Mergesort make a recursve call to sort ts rght subarray: base case, so return to the call for the subarray {12, 8:

32 Tracng the Calls to Mergesort merge the sorted halves of {12, 8: end of the method, so return to the call for the 4-element subarray, whch now has a sorted left subarray: Tracng the Calls to Mergesort make a recursve call to sort the rght subarray of the 4-element subarray splt t nto two 1-element subarrays, and make a recursve call to sort the left subarray: base case

33 Tracng the Calls to Mergesort return to the call for the subarray {14, 4: make a recursve call to sort ts rght subarray: base case Tracng the Calls to Mergesort return to the call for the subarray {14, 4: merge the sorted halves of {14, 4:

34 Tracng the Calls to Mergesort end of the method, so return to the call for the 4-element subarray, whch now has two sorted 2-element subarrays: merge the 2-element subarrays: Tracng the Calls to Mergesort end of the method, so return to the call for the orgnal array, whch now has a sorted left subarray: perform a smlar set of recursve calls to sort the rght subarray. here's the result: fnally, merge the sorted 4-element subarrays to get a fully sorted 8-element array:

35 Implementng Mergesort One approach s to create new arrays for each new set of subarrays, and to merge them back nto the array that was splt. Instead, we'll create a temp. array of the same sze as the orgnal. pass t to each call of the recursve mergesort method use t when mergng subarrays of the orgnal array: arr temp after each merge, copy the result back nto the orgnal array: arr temp A Method for Mergng Subarrays prvate statc vod merge(nt[] arr, nt[] temp, nt leftstart, nt leftend, nt rghtstart, nt rghtend) { nt = leftstart; // ndex nto left subarray nt j = rghtstart; // ndex nto rght subarray nt k = leftstart; // ndex nto temp whle ( <= leftend && j <= rghtend) { f (arr[] < arr[j]) { temp[k] = arr[]; ++; k++; else { temp[k] = arr[j]; j++; k++; whle ( <= leftend) { temp[k] = arr[]; ++; k++; whle (j <= rghtend) { temp[k] = arr[j]; j++; k++; for ( = leftstart; <= rghtend; ++) { arr[] = temp[];

36 A Method for Mergng Subarrays prvate statc vod merge(nt[] arr, nt[] temp, nt leftstart, nt leftend, nt rghtstart, nt rghtend) { nt = leftstart; // ndex nto left subarray nt j = rghtstart; // ndex nto rght subarray nt k = leftstart; // ndex nto temp whle ( <= leftend && j <= rghtend) { // both subarrays stll have values f (arr[] < arr[j]) { temp[k] = arr[]; ++; k++; else { temp[k] = arr[j]; j++; k++;... leftstart leftend rghtstart rghtend arr: temp: Methods for Mergesort Here's the key recursve method: prvate statc vod msort(nt[] arr, nt[] temp, nt start, nt end){ f (start >= end) { // base case: subarray of length 0 or 1 return; else { nt mddle = (start + end)/2; msort(arr, temp, start, mddle); msort(arr, temp, mddle + 1, end); merge(arr, temp, start, mddle, mddle + 1, end); arr: start end temp:

37 Methods for Mergesort Here's the key recursve method: prvate statc vod msort(nt[] arr, nt[] temp, nt start, nt end){ f (start >= end) { // base case: subarray of length 0 or 1 return; else { nt mddle = (start + end)/2; msort(arr, temp, start, mddle); msort(arr, temp, mddle + 1, end); merge(arr, temp, start, mddle, mddle + 1, end); We use a "wrapper" method to create the temp array, and to make the ntal call to the recursve method: publc statc vod mergesort(nt[] arr) { nt[] temp = new nt[arr.length]; msort(arr, temp, 0, arr.length - 1); Tme Analyss of Mergesort Mergng two halves of an array of sze n requres 2n moves. Why? Mergesort repeatedly dvdes the array n half, so we have the followng call tree (showng the szes of the arrays): moves n 2n n/2 n/2 2*2*(n/2) = 2n n/4 n/4 n/4 n/4 4*2*(n/4) = 2n at all but the last level of the call tree, there are 2n moves how many levels are there? M(n) =? C(n) =?

38 Summary: Comparson-Based Sortng Algorthms algorthm best case avg case worst case extra memory selecton sort O(n 2 ) O(n 2 ) O(n 2 ) O(1) nserton sort O(n) O(n 2 ) O(n 2 ) O(1) Shell sort O(n log n) O(n 1.5 ) O(n 1.5 ) O(1) bubble sort O(n 2 ) O(n 2 ) O(n 2 ) O(1) qucksort O(n log n) O(n log n) O(n 2 ) O(1) mergesort O(n log n) O(n log n) O(nlog n) O(n) Inserton sort s best for nearly sorted arrays. Mergesort has the best worst-case complexty, but requres extra memory and moves to and from the temp array. Qucksort s comparable to mergesort n the average case. Wth a reasonable pvot choce, ts worst case s seldom seen. Use SortCount.java to experment. Comparson-Based vs. Dstrbutve Sortng Untl now, all of the sortng algorthms we have consdered have been comparson-based: treat the keys as wholes (comparng them) don t take them apart n any way all that matters s the relatve order of the keys, not ther actual values. No comparson-based sortng algorthm can do better than O(n log 2 n) on an array of length n. O(n log 2 n) s a lower bound for such algorthms. Dstrbutve sortng algorthms do more than compare keys; they perform calculatons on the values of ndvdual keys. Movng beyond comparsons allows us to overcome the lower bound. tradeoff: use more memory.

39 Dstrbutve Sortng Example: Radx Sort Reles on the representaton of the data as a sequence of m quanttes wth k possble values. Examples: m k nteger n range strng of 15 upper-case letters bt nteger 32 2 (n bnary) (as bytes) Strategy: Dstrbute accordng to the last element n the sequence, then concatenate the results: get: Repeat, movng back one dgt each tme: get: Analyss of Radx Sort Recall that we treat the values as a sequence of m quanttes wth k possble values. Number of operatons s O(n*m) for an array wth n elements better than O(n log n) when m < log n Memory usage ncreases as k ncreases. k tends to ncrease as m decreases tradeoff: ncreased speed requres ncreased memory usage

40 Bg-O Notaton Revsted We've seen that we can group functons nto classes by focusng on the fastest-growng term n the expresson for the number of operatons that they perform. e.g., an algorthm that performs n 2 /2 n/2 operatons s a O(n 2 )-tme or quadratc-tme algorthm Common classes of algorthms: name example expressons bg-o notaton constant tme 1, 7, 10 O(1) logarthmc tme 3log 10 n, log 2 n+5 O(log n) lnear tme 5n, 10n 2log 2 n O(n) nlogn tme 4nlog 2 n, nlog 2 n+n O(nlog n) quadratc tme 2n 2 + 3n, n 2 1 O(n 2 ) cubc tme n 2 +3n 3, 5n 3 5 O(n 3 ) exponental tme 2 n, 5e n +2n 2 O(c n ) factoral tme 3n!, 5n + n! O(n!) slower How Does the Number of Operatons Scale? Let's say that we have a problem sze of 1000, and we measure the number of operatons performed by a gven algorthm. If we double the problem sze to 2000, how would the number of operatons performed by an algorthm ncrease f t s: O(n)-tme O(n 2 )-tme O(n 3 )-tme O(log 2 n)-tme O(2 n )-tme

41 How Does the Actual Runnng Tme Scale? How much tme s requred to solve a problem of sze n? assume that each operaton requres 1 sec (1 x 10-6 sec) tme functon problem sze (n) n s s s s s s n s.0004 s.0009 s.0016 s.0025 s.0036 s n 5.1 s 3.2 s 24.3 s 1.7 mn 5.2 mn 13.0 mn 2 n.001 s 1.0 s 17.9 mn 12.7 days 35.7 yrs 36,600 yrs sample computatons: when n = 10, an n 2 algorthm performs 10 2 operatons * (1 x 10-6 sec) =.0001 sec when n = 30, a 2 n algorthm performs 2 30 operatons * (1 x 10-6 sec) = 1073 sec = 17.9 mn What's the Largest Problem That Can Be Solved? What's the largest problem sze n that can be solved n a gven tme T? (agan assume 1 sec per operaton) tme functon tme avalable (T) 1 mn 1 hour 1 week 1 year n 60,000, x x x n , ,688 5,615,692 n n sample computatons: 1 hour = 3600 sec that's enough tme for 3600/(1 x 10-6 ) = 3.6 x 10 9 operatons n 2 algorthm: n 2 = 3.6 x 10 9 n = (3.6 x 10 9 ) 1/2 = 60,000 2 n algorthm: 2 n = 3.6 x 10 9 n = log 2 (3.6 x 10 9 ) ~= 31

CSCI 104 Sorting Algorithms. Mark Redekopp David Kempe

CSCI 104 Sorting Algorithms. Mark Redekopp David Kempe CSCI 104 Sortng Algorthms Mark Redekopp Davd Kempe Algorthm Effcency SORTING 2 Sortng If we have an unordered lst, sequental search becomes our only choce If we wll perform a lot of searches t may be benefcal

More information

Sequential search. Building Java Programs Chapter 13. Sequential search. Sequential search

Sequential search. Building Java Programs Chapter 13. Sequential search. Sequential search Sequental search Buldng Java Programs Chapter 13 Searchng and Sortng sequental search: Locates a target value n an array/lst by examnng each element from start to fnsh. How many elements wll t need to

More information

Today s Outline. Sorting: The Big Picture. Why Sort? Selection Sort: Idea. Insertion Sort: Idea. Sorting Chapter 7 in Weiss.

Today s Outline. Sorting: The Big Picture. Why Sort? Selection Sort: Idea. Insertion Sort: Idea. Sorting Chapter 7 in Weiss. Today s Outlne Sortng Chapter 7 n Wess CSE 26 Data Structures Ruth Anderson Announcements Wrtten Homework #6 due Frday 2/26 at the begnnng of lecture Proect Code due Mon March 1 by 11pm Today s Topcs:

More information

Sorting: The Big Picture. The steps of QuickSort. QuickSort Example. QuickSort Example. QuickSort Example. Recursive Quicksort

Sorting: The Big Picture. The steps of QuickSort. QuickSort Example. QuickSort Example. QuickSort Example. Recursive Quicksort Sortng: The Bg Pcture Gven n comparable elements n an array, sort them n an ncreasng (or decreasng) order. Smple algorthms: O(n ) Inserton sort Selecton sort Bubble sort Shell sort Fancer algorthms: O(n

More information

Sorting Review. Sorting. Comparison Sorting. CSE 680 Prof. Roger Crawfis. Assumptions

Sorting Review. Sorting. Comparison Sorting. CSE 680 Prof. Roger Crawfis. Assumptions Sortng Revew Introducton to Algorthms Qucksort CSE 680 Prof. Roger Crawfs Inserton Sort T(n) = Θ(n 2 ) In-place Merge Sort T(n) = Θ(n lg(n)) Not n-place Selecton Sort (from homework) T(n) = Θ(n 2 ) In-place

More information

Insertion Sort. Divide and Conquer Sorting. Divide and Conquer. Mergesort. Mergesort Example. Auxiliary Array

Insertion Sort. Divide and Conquer Sorting. Divide and Conquer. Mergesort. Mergesort Example. Auxiliary Array Inserton Sort Dvde and Conquer Sortng CSE 6 Data Structures Lecture 18 What f frst k elements of array are already sorted? 4, 7, 1, 5, 1, 16 We can shft the tal of the sorted elements lst down and then

More information

Sorting. Sorted Original. index. index

Sorting. Sorted Original. index. index 1 Unt 16 Sortng 2 Sortng Sortng requres us to move data around wthn an array Allows users to see and organze data more effcently Behnd the scenes t allows more effectve searchng of data There are MANY

More information

Sorting. Sorting. Why Sort? Consistent Ordering

Sorting. Sorting. Why Sort? Consistent Ordering Sortng CSE 6 Data Structures Unt 15 Readng: Sectons.1-. Bubble and Insert sort,.5 Heap sort, Secton..6 Radx sort, Secton.6 Mergesort, Secton. Qucksort, Secton.8 Lower bound Sortng Input an array A of data

More information

CSE 326: Data Structures Quicksort Comparison Sorting Bound

CSE 326: Data Structures Quicksort Comparison Sorting Bound CSE 326: Data Structures Qucksort Comparson Sortng Bound Bran Curless Sprng 2008 Announcements (5/14/08) Homework due at begnnng of class on Frday. Secton tomorrow: Graded homeworks returned More dscusson

More information

CSE 326: Data Structures Quicksort Comparison Sorting Bound

CSE 326: Data Structures Quicksort Comparison Sorting Bound CSE 326: Data Structures Qucksort Comparson Sortng Bound Steve Setz Wnter 2009 Qucksort Qucksort uses a dvde and conquer strategy, but does not requre the O(N) extra space that MergeSort does. Here s the

More information

Searching & Sorting. Definitions of Search and Sort. Linear Search in C++ Linear Search. Week 11. index to the item, or -1 if not found.

Searching & Sorting. Definitions of Search and Sort. Linear Search in C++ Linear Search. Week 11. index to the item, or -1 if not found. Searchng & Sortng Wee 11 Gadds: 8, 19.6,19.8 CS 5301 Sprng 2014 Jll Seaman 1 Defntons of Search and Sort Search: fnd a gven tem n a lst, return the ndex to the tem, or -1 f not found. Sort: rearrange the

More information

Course Introduction. Algorithm 8/31/2017. COSC 320 Advanced Data Structures and Algorithms. COSC 320 Advanced Data Structures and Algorithms

Course Introduction. Algorithm 8/31/2017. COSC 320 Advanced Data Structures and Algorithms. COSC 320 Advanced Data Structures and Algorithms Course Introducton Course Topcs Exams, abs, Proects A quc loo at a few algorthms 1 Advanced Data Structures and Algorthms Descrpton: We are gong to dscuss algorthm complexty analyss, algorthm desgn technques

More information

Problem Set 3 Solutions

Problem Set 3 Solutions Introducton to Algorthms October 4, 2002 Massachusetts Insttute of Technology 6046J/18410J Professors Erk Demane and Shaf Goldwasser Handout 14 Problem Set 3 Solutons (Exercses were not to be turned n,

More information

CS1100 Introduction to Programming

CS1100 Introduction to Programming Factoral (n) Recursve Program fact(n) = n*fact(n-) CS00 Introducton to Programmng Recurson and Sortng Madhu Mutyam Department of Computer Scence and Engneerng Indan Insttute of Technology Madras nt fact

More information

Programming in Fortran 90 : 2017/2018

Programming in Fortran 90 : 2017/2018 Programmng n Fortran 90 : 2017/2018 Programmng n Fortran 90 : 2017/2018 Exercse 1 : Evaluaton of functon dependng on nput Wrte a program who evaluate the functon f (x,y) for any two user specfed values

More information

Quicksort. Part 1: Understanding Quicksort

Quicksort. Part 1: Understanding Quicksort Qucksort Part 1: Understandng Qucksort https://www.youtube.com/watch?v=ywwby6j5gz8 Qucksort A practcal algorthm The hdden constants are small (hdden by Bg-O) Succnct algorthm The runnng tme = O(n lg n)

More information

CS240: Programming in C. Lecture 12: Polymorphic Sorting

CS240: Programming in C. Lecture 12: Polymorphic Sorting CS240: Programmng n C ecture 12: Polymorphc Sortng Sortng Gven a collecton of tems and a total order over them, sort the collecton under ths order. Total order: every tem s ordered wth respect to every

More information

Priority queues and heaps Professors Clark F. Olson and Carol Zander

Priority queues and heaps Professors Clark F. Olson and Carol Zander Prorty queues and eaps Professors Clark F. Olson and Carol Zander Prorty queues A common abstract data type (ADT) n computer scence s te prorty queue. As you mgt expect from te name, eac tem n te prorty

More information

CE 221 Data Structures and Algorithms

CE 221 Data Structures and Algorithms CE 1 ata Structures and Algorthms Chapter 4: Trees BST Text: Read Wess, 4.3 Izmr Unversty of Economcs 1 The Search Tree AT Bnary Search Trees An mportant applcaton of bnary trees s n searchng. Let us assume

More information

Brave New World Pseudocode Reference

Brave New World Pseudocode Reference Brave New World Pseudocode Reference Pseudocode s a way to descrbe how to accomplsh tasks usng basc steps lke those a computer mght perform. In ths week s lab, you'll see how a form of pseudocode can be

More information

Design and Analysis of Algorithms

Design and Analysis of Algorithms Desgn and Analyss of Algorthms Heaps and Heapsort Reference: CLRS Chapter 6 Topcs: Heaps Heapsort Prorty queue Huo Hongwe Recap and overvew The story so far... Inserton sort runnng tme of Θ(n 2 ); sorts

More information

Assignment # 2. Farrukh Jabeen Algorithms 510 Assignment #2 Due Date: June 15, 2009.

Assignment # 2. Farrukh Jabeen Algorithms 510 Assignment #2 Due Date: June 15, 2009. Farrukh Jabeen Algorthms 51 Assgnment #2 Due Date: June 15, 29. Assgnment # 2 Chapter 3 Dscrete Fourer Transforms Implement the FFT for the DFT. Descrbed n sectons 3.1 and 3.2. Delverables: 1. Concse descrpton

More information

News. Recap: While Loop Example. Reading. Recap: Do Loop Example. Recap: For Loop Example

News. Recap: While Loop Example. Reading. Recap: Do Loop Example. Recap: For Loop Example Unversty of Brtsh Columba CPSC, Intro to Computaton Jan-Apr Tamara Munzner News Assgnment correctons to ASCIIArtste.java posted defntely read WebCT bboards Arrays Lecture, Tue Feb based on sldes by Kurt

More information

Machine Learning: Algorithms and Applications

Machine Learning: Algorithms and Applications 14/05/1 Machne Learnng: Algorthms and Applcatons Florano Zn Free Unversty of Bozen-Bolzano Faculty of Computer Scence Academc Year 011-01 Lecture 10: 14 May 01 Unsupervsed Learnng cont Sldes courtesy of

More information

An Optimal Algorithm for Prufer Codes *

An Optimal Algorithm for Prufer Codes * J. Software Engneerng & Applcatons, 2009, 2: 111-115 do:10.4236/jsea.2009.22016 Publshed Onlne July 2009 (www.scrp.org/journal/jsea) An Optmal Algorthm for Prufer Codes * Xaodong Wang 1, 2, Le Wang 3,

More information

More on Sorting: Quick Sort and Heap Sort

More on Sorting: Quick Sort and Heap Sort More on Sortng: Quck Sort and Heap Sort Antono Carzanga Faculty of Informatcs Unversty of Lugano October 12, 2007 c 2006 Antono Carzanga 1 Another dvde-and-conuer sortng algorthm The heap Heap sort Outlne

More information

CS221: Algorithms and Data Structures. Priority Queues and Heaps. Alan J. Hu (Borrowing slides from Steve Wolfman)

CS221: Algorithms and Data Structures. Priority Queues and Heaps. Alan J. Hu (Borrowing slides from Steve Wolfman) CS: Algorthms and Data Structures Prorty Queues and Heaps Alan J. Hu (Borrowng sldes from Steve Wolfman) Learnng Goals After ths unt, you should be able to: Provde examples of approprate applcatons for

More information

Complex Numbers. Now we also saw that if a and b were both positive then ab = a b. For a second let s forget that restriction and do the following.

Complex Numbers. Now we also saw that if a and b were both positive then ab = a b. For a second let s forget that restriction and do the following. Complex Numbers The last topc n ths secton s not really related to most of what we ve done n ths chapter, although t s somewhat related to the radcals secton as we wll see. We also won t need the materal

More information

Array transposition in CUDA shared memory

Array transposition in CUDA shared memory Array transposton n CUDA shared memory Mke Gles February 19, 2014 Abstract Ths short note s nspred by some code wrtten by Jeremy Appleyard for the transposton of data through shared memory. I had some

More information

ELEC 377 Operating Systems. Week 6 Class 3

ELEC 377 Operating Systems. Week 6 Class 3 ELEC 377 Operatng Systems Week 6 Class 3 Last Class Memory Management Memory Pagng Pagng Structure ELEC 377 Operatng Systems Today Pagng Szes Vrtual Memory Concept Demand Pagng ELEC 377 Operatng Systems

More information

Outline. Midterm Review. Declaring Variables. Main Variable Data Types. Symbolic Constants. Arithmetic Operators. Midterm Review March 24, 2014

Outline. Midterm Review. Declaring Variables. Main Variable Data Types. Symbolic Constants. Arithmetic Operators. Midterm Review March 24, 2014 Mdterm Revew March 4, 4 Mdterm Revew Larry Caretto Mechancal Engneerng 9 Numercal Analyss of Engneerng Systems March 4, 4 Outlne VBA and MATLAB codng Varable types Control structures (Loopng and Choce)

More information

Mathematics 256 a course in differential equations for engineering students

Mathematics 256 a course in differential equations for engineering students Mathematcs 56 a course n dfferental equatons for engneerng students Chapter 5. More effcent methods of numercal soluton Euler s method s qute neffcent. Because the error s essentally proportonal to the

More information

CHAPTER 10: ALGORITHM DESIGN TECHNIQUES

CHAPTER 10: ALGORITHM DESIGN TECHNIQUES CHAPTER 10: ALGORITHM DESIGN TECHNIQUES So far, we have been concerned wth the effcent mplementaton of algorthms. We have seen that when an algorthm s gven, the actual data structures need not be specfed.

More information

CMPS 10 Introduction to Computer Science Lecture Notes

CMPS 10 Introduction to Computer Science Lecture Notes CPS 0 Introducton to Computer Scence Lecture Notes Chapter : Algorthm Desgn How should we present algorthms? Natural languages lke Englsh, Spansh, or French whch are rch n nterpretaton and meanng are not

More information

Parallelism for Nested Loops with Non-uniform and Flow Dependences

Parallelism for Nested Loops with Non-uniform and Flow Dependences Parallelsm for Nested Loops wth Non-unform and Flow Dependences Sam-Jn Jeong Dept. of Informaton & Communcaton Engneerng, Cheonan Unversty, 5, Anseo-dong, Cheonan, Chungnam, 330-80, Korea. seong@cheonan.ac.kr

More information

For instance, ; the five basic number-sets are increasingly more n A B & B A A = B (1)

For instance, ; the five basic number-sets are increasingly more n A B & B A A = B (1) Secton 1.2 Subsets and the Boolean operatons on sets If every element of the set A s an element of the set B, we say that A s a subset of B, or that A s contaned n B, or that B contans A, and we wrte A

More information

Conditional Speculative Decimal Addition*

Conditional Speculative Decimal Addition* Condtonal Speculatve Decmal Addton Alvaro Vazquez and Elsardo Antelo Dep. of Electronc and Computer Engneerng Unv. of Santago de Compostela, Span Ths work was supported n part by Xunta de Galca under grant

More information

Kent State University CS 4/ Design and Analysis of Algorithms. Dept. of Math & Computer Science LECT-16. Dynamic Programming

Kent State University CS 4/ Design and Analysis of Algorithms. Dept. of Math & Computer Science LECT-16. Dynamic Programming CS 4/560 Desgn and Analyss of Algorthms Kent State Unversty Dept. of Math & Computer Scence LECT-6 Dynamc Programmng 2 Dynamc Programmng Dynamc Programmng, lke the dvde-and-conquer method, solves problems

More information

Intro. Iterators. 1. Access

Intro. Iterators. 1. Access Intro Ths mornng I d lke to talk a lttle bt about s and s. We wll start out wth smlartes and dfferences, then we wll see how to draw them n envronment dagrams, and we wll fnsh wth some examples. Happy

More information

6.854 Advanced Algorithms Petar Maymounkov Problem Set 11 (November 23, 2005) With: Benjamin Rossman, Oren Weimann, and Pouya Kheradpour

6.854 Advanced Algorithms Petar Maymounkov Problem Set 11 (November 23, 2005) With: Benjamin Rossman, Oren Weimann, and Pouya Kheradpour 6.854 Advanced Algorthms Petar Maymounkov Problem Set 11 (November 23, 2005) Wth: Benjamn Rossman, Oren Wemann, and Pouya Kheradpour Problem 1. We reduce vertex cover to MAX-SAT wth weghts, such that the

More information

Performance Evaluation of Information Retrieval Systems

Performance Evaluation of Information Retrieval Systems Why System Evaluaton? Performance Evaluaton of Informaton Retreval Systems Many sldes n ths secton are adapted from Prof. Joydeep Ghosh (UT ECE) who n turn adapted them from Prof. Dk Lee (Unv. of Scence

More information

The Greedy Method. Outline and Reading. Change Money Problem. Greedy Algorithms. Applications of the Greedy Strategy. The Greedy Method Technique

The Greedy Method. Outline and Reading. Change Money Problem. Greedy Algorithms. Applications of the Greedy Strategy. The Greedy Method Technique //00 :0 AM Outlne and Readng The Greedy Method The Greedy Method Technque (secton.) Fractonal Knapsack Problem (secton..) Task Schedulng (secton..) Mnmum Spannng Trees (secton.) Change Money Problem Greedy

More information

Compiler Design. Spring Register Allocation. Sample Exercises and Solutions. Prof. Pedro C. Diniz

Compiler Design. Spring Register Allocation. Sample Exercises and Solutions. Prof. Pedro C. Diniz Compler Desgn Sprng 2014 Regster Allocaton Sample Exercses and Solutons Prof. Pedro C. Dnz USC / Informaton Scences Insttute 4676 Admralty Way, Sute 1001 Marna del Rey, Calforna 90292 pedro@s.edu Regster

More information

Esc101 Lecture 1 st April, 2008 Generating Permutation

Esc101 Lecture 1 st April, 2008 Generating Permutation Esc101 Lecture 1 Aprl, 2008 Generatng Permutaton In ths class we wll look at a problem to wrte a program that takes as nput 1,2,...,N and prnts out all possble permutatons of the numbers 1,2,...,N. For

More information

Hierarchical clustering for gene expression data analysis

Hierarchical clustering for gene expression data analysis Herarchcal clusterng for gene expresson data analyss Gorgo Valentn e-mal: valentn@ds.unm.t Clusterng of Mcroarray Data. Clusterng of gene expresson profles (rows) => dscovery of co-regulated and functonally

More information

Support Vector Machines

Support Vector Machines /9/207 MIST.6060 Busness Intellgence and Data Mnng What are Support Vector Machnes? Support Vector Machnes Support Vector Machnes (SVMs) are supervsed learnng technques that analyze data and recognze patterns.

More information

Parallel Numerics. 1 Preconditioning & Iterative Solvers (From 2016)

Parallel Numerics. 1 Preconditioning & Iterative Solvers (From 2016) Technsche Unverstät München WSe 6/7 Insttut für Informatk Prof. Dr. Thomas Huckle Dpl.-Math. Benjamn Uekermann Parallel Numercs Exercse : Prevous Exam Questons Precondtonng & Iteratve Solvers (From 6)

More information

Solutions to Programming Assignment Five Interpolation and Numerical Differentiation

Solutions to Programming Assignment Five Interpolation and Numerical Differentiation College of Engneerng and Coputer Scence Mechancal Engneerng Departent Mechancal Engneerng 309 Nuercal Analyss of Engneerng Systes Sprng 04 Nuber: 537 Instructor: Larry Caretto Solutons to Prograng Assgnent

More information

R s s f. m y s. SPH3UW Unit 7.3 Spherical Concave Mirrors Page 1 of 12. Notes

R s s f. m y s. SPH3UW Unit 7.3 Spherical Concave Mirrors Page 1 of 12. Notes SPH3UW Unt 7.3 Sphercal Concave Mrrors Page 1 of 1 Notes Physcs Tool box Concave Mrror If the reflectng surface takes place on the nner surface of the sphercal shape so that the centre of the mrror bulges

More information

Private Information Retrieval (PIR)

Private Information Retrieval (PIR) 2 Levente Buttyán Problem formulaton Alce wants to obtan nformaton from a database, but she does not want the database to learn whch nformaton she wanted e.g., Alce s an nvestor queryng a stock-market

More information

Lecture 5: Multilayer Perceptrons

Lecture 5: Multilayer Perceptrons Lecture 5: Multlayer Perceptrons Roger Grosse 1 Introducton So far, we ve only talked about lnear models: lnear regresson and lnear bnary classfers. We noted that there are functons that can t be represented

More information

High level vs Low Level. What is a Computer Program? What does gcc do for you? Program = Instructions + Data. Basic Computer Organization

High level vs Low Level. What is a Computer Program? What does gcc do for you? Program = Instructions + Data. Basic Computer Organization What s a Computer Program? Descrpton of algorthms and data structures to acheve a specfc ojectve Could e done n any language, even a natural language lke Englsh Programmng language: A Standard notaton

More information

Parallel matrix-vector multiplication

Parallel matrix-vector multiplication Appendx A Parallel matrx-vector multplcaton The reduced transton matrx of the three-dmensonal cage model for gel electrophoress, descrbed n secton 3.2, becomes excessvely large for polymer lengths more

More information

Greedy Technique - Definition

Greedy Technique - Definition Greedy Technque Greedy Technque - Defnton The greedy method s a general algorthm desgn paradgm, bult on the follong elements: confguratons: dfferent choces, collectons, or values to fnd objectve functon:

More information

NUMERICAL SOLVING OPTIMAL CONTROL PROBLEMS BY THE METHOD OF VARIATIONS

NUMERICAL SOLVING OPTIMAL CONTROL PROBLEMS BY THE METHOD OF VARIATIONS ARPN Journal of Engneerng and Appled Scences 006-017 Asan Research Publshng Network (ARPN). All rghts reserved. NUMERICAL SOLVING OPTIMAL CONTROL PROBLEMS BY THE METHOD OF VARIATIONS Igor Grgoryev, Svetlana

More information

CHARUTAR VIDYA MANDAL S SEMCOM Vallabh Vidyanagar

CHARUTAR VIDYA MANDAL S SEMCOM Vallabh Vidyanagar CHARUTAR VIDYA MANDAL S SEMCOM Vallabh Vdyanagar Faculty Name: Am D. Trved Class: SYBCA Subject: US03CBCA03 (Advanced Data & Fle Structure) *UNIT 1 (ARRAYS AND TREES) **INTRODUCTION TO ARRAYS If we want

More information

Loop Transformations, Dependences, and Parallelization

Loop Transformations, Dependences, and Parallelization Loop Transformatons, Dependences, and Parallelzaton Announcements Mdterm s Frday from 3-4:15 n ths room Today Semester long project Data dependence recap Parallelsm and storage tradeoff Scalar expanson

More information

CS 534: Computer Vision Model Fitting

CS 534: Computer Vision Model Fitting CS 534: Computer Vson Model Fttng Sprng 004 Ahmed Elgammal Dept of Computer Scence CS 534 Model Fttng - 1 Outlnes Model fttng s mportant Least-squares fttng Maxmum lkelhood estmaton MAP estmaton Robust

More information

Virtual Memory. Background. No. 10. Virtual Memory: concept. Logical Memory Space (review) Demand Paging(1) Virtual Memory

Virtual Memory. Background. No. 10. Virtual Memory: concept. Logical Memory Space (review) Demand Paging(1) Virtual Memory Background EECS. Operatng System Fundamentals No. Vrtual Memory Prof. Hu Jang Department of Electrcal Engneerng and Computer Scence, York Unversty Memory-management methods normally requres the entre process

More information

A Fast Content-Based Multimedia Retrieval Technique Using Compressed Data

A Fast Content-Based Multimedia Retrieval Technique Using Compressed Data A Fast Content-Based Multmeda Retreval Technque Usng Compressed Data Borko Furht and Pornvt Saksobhavvat NSF Multmeda Laboratory Florda Atlantc Unversty, Boca Raton, Florda 3343 ABSTRACT In ths paper,

More information

S1 Note. Basis functions.

S1 Note. Basis functions. S1 Note. Bass functons. Contents Types of bass functons...1 The Fourer bass...2 B-splne bass...3 Power and type I error rates wth dfferent numbers of bass functons...4 Table S1. Smulaton results of type

More information

Exercises (Part 4) Introduction to R UCLA/CCPR. John Fox, February 2005

Exercises (Part 4) Introduction to R UCLA/CCPR. John Fox, February 2005 Exercses (Part 4) Introducton to R UCLA/CCPR John Fox, February 2005 1. A challengng problem: Iterated weghted least squares (IWLS) s a standard method of fttng generalzed lnear models to data. As descrbed

More information

X- Chart Using ANOM Approach

X- Chart Using ANOM Approach ISSN 1684-8403 Journal of Statstcs Volume 17, 010, pp. 3-3 Abstract X- Chart Usng ANOM Approach Gullapall Chakravarth 1 and Chaluvad Venkateswara Rao Control lmts for ndvdual measurements (X) chart are

More information

Support Vector Machines

Support Vector Machines Support Vector Machnes Decson surface s a hyperplane (lne n 2D) n feature space (smlar to the Perceptron) Arguably, the most mportant recent dscovery n machne learnng In a nutshell: map the data to a predetermned

More information

3D vector computer graphics

3D vector computer graphics 3D vector computer graphcs Paolo Varagnolo: freelance engneer Padova Aprl 2016 Prvate Practce ----------------------------------- 1. Introducton Vector 3D model representaton n computer graphcs requres

More information

Computer models of motion: Iterative calculations

Computer models of motion: Iterative calculations Computer models o moton: Iteratve calculatons OBJECTIVES In ths actvty you wll learn how to: Create 3D box objects Update the poston o an object teratvely (repeatedly) to anmate ts moton Update the momentum

More information

Terminal Window. 11. Section 7 Exercises Program Memory Exercise 7-1 Swap Values in an Array Working memory Global Memory. 2 nd call 3 rd call

Terminal Window. 11. Section 7 Exercises Program Memory Exercise 7-1 Swap Values in an Array Working memory Global Memory. 2 nd call 3 rd call 11. Secton 7 Exercses Program Memory Exercse 7-1 Swap Values n an Array Workng memory Global Memory class SwapTlYouDrop publc statc vod man (Strng args[ ]) nt = 0; nt a; a = new nt[] 2, 4, 6, 8, 10, 12

More information

USING GRAPHING SKILLS

USING GRAPHING SKILLS Name: BOLOGY: Date: _ Class: USNG GRAPHNG SKLLS NTRODUCTON: Recorded data can be plotted on a graph. A graph s a pctoral representaton of nformaton recorded n a data table. t s used to show a relatonshp

More information

Loop Transformations for Parallelism & Locality. Review. Scalar Expansion. Scalar Expansion: Motivation

Loop Transformations for Parallelism & Locality. Review. Scalar Expansion. Scalar Expansion: Motivation Loop Transformatons for Parallelsm & Localty Last week Data dependences and loops Loop transformatons Parallelzaton Loop nterchange Today Scalar expanson for removng false dependences Loop nterchange Loop

More information

Subspace clustering. Clustering. Fundamental to all clustering techniques is the choice of distance measure between data points;

Subspace clustering. Clustering. Fundamental to all clustering techniques is the choice of distance measure between data points; Subspace clusterng Clusterng Fundamental to all clusterng technques s the choce of dstance measure between data ponts; D q ( ) ( ) 2 x x = x x, j k = 1 k jk Squared Eucldean dstance Assumpton: All features

More information

Hermite Splines in Lie Groups as Products of Geodesics

Hermite Splines in Lie Groups as Products of Geodesics Hermte Splnes n Le Groups as Products of Geodescs Ethan Eade Updated May 28, 2017 1 Introducton 1.1 Goal Ths document defnes a curve n the Le group G parametrzed by tme and by structural parameters n the

More information

Life Tables (Times) Summary. Sample StatFolio: lifetable times.sgp

Life Tables (Times) Summary. Sample StatFolio: lifetable times.sgp Lfe Tables (Tmes) Summary... 1 Data Input... 2 Analyss Summary... 3 Survval Functon... 5 Log Survval Functon... 6 Cumulatve Hazard Functon... 7 Percentles... 7 Group Comparsons... 8 Summary The Lfe Tables

More information

such that is accepted of states in , where Finite Automata Lecture 2-1: Regular Languages be an FA. A string is the transition function,

such that is accepted of states in , where Finite Automata Lecture 2-1: Regular Languages be an FA. A string is the transition function, * Lecture - Regular Languages S Lecture - Fnte Automata where A fnte automaton s a -tuple s a fnte set called the states s a fnte set called the alphabet s the transton functon s the ntal state s the set

More information

NAG Fortran Library Chapter Introduction. G10 Smoothing in Statistics

NAG Fortran Library Chapter Introduction. G10 Smoothing in Statistics Introducton G10 NAG Fortran Lbrary Chapter Introducton G10 Smoothng n Statstcs Contents 1 Scope of the Chapter... 2 2 Background to the Problems... 2 2.1 Smoothng Methods... 2 2.2 Smoothng Splnes and Regresson

More information

Concurrent Apriori Data Mining Algorithms

Concurrent Apriori Data Mining Algorithms Concurrent Apror Data Mnng Algorthms Vassl Halatchev Department of Electrcal Engneerng and Computer Scence York Unversty, Toronto October 8, 2015 Outlne Why t s mportant Introducton to Assocaton Rule Mnng

More information

Load Balancing for Hex-Cell Interconnection Network

Load Balancing for Hex-Cell Interconnection Network Int. J. Communcatons, Network and System Scences,,, - Publshed Onlne Aprl n ScRes. http://www.scrp.org/journal/jcns http://dx.do.org/./jcns.. Load Balancng for Hex-Cell Interconnecton Network Saher Manaseer,

More information

Analysis of Continuous Beams in General

Analysis of Continuous Beams in General Analyss of Contnuous Beams n General Contnuous beams consdered here are prsmatc, rgdly connected to each beam segment and supported at varous ponts along the beam. onts are selected at ponts of support,

More information

Wishing you all a Total Quality New Year!

Wishing you all a Total Quality New Year! Total Qualty Management and Sx Sgma Post Graduate Program 214-15 Sesson 4 Vnay Kumar Kalakband Assstant Professor Operatons & Systems Area 1 Wshng you all a Total Qualty New Year! Hope you acheve Sx sgma

More information

Lecture 3: Computer Arithmetic: Multiplication and Division

Lecture 3: Computer Arithmetic: Multiplication and Division 8-447 Lecture 3: Computer Arthmetc: Multplcaton and Dvson James C. Hoe Dept of ECE, CMU January 26, 29 S 9 L3- Announcements: Handout survey due Lab partner?? Read P&H Ch 3 Read IEEE 754-985 Handouts:

More information

Agenda & Reading. Simple If. Decision-Making Statements. COMPSCI 280 S1C Applications Programming. Programming Fundamentals

Agenda & Reading. Simple If. Decision-Making Statements. COMPSCI 280 S1C Applications Programming. Programming Fundamentals Agenda & Readng COMPSCI 8 SC Applcatons Programmng Programmng Fundamentals Control Flow Agenda: Decsonmakng statements: Smple If, Ifelse, nested felse, Select Case s Whle, DoWhle/Untl, For, For Each, Nested

More information

A Binarization Algorithm specialized on Document Images and Photos

A Binarization Algorithm specialized on Document Images and Photos A Bnarzaton Algorthm specalzed on Document mages and Photos Ergna Kavalleratou Dept. of nformaton and Communcaton Systems Engneerng Unversty of the Aegean kavalleratou@aegean.gr Abstract n ths paper, a

More information

GSLM Operations Research II Fall 13/14

GSLM Operations Research II Fall 13/14 GSLM 58 Operatons Research II Fall /4 6. Separable Programmng Consder a general NLP mn f(x) s.t. g j (x) b j j =. m. Defnton 6.. The NLP s a separable program f ts objectve functon and all constrants are

More information

Pass by Reference vs. Pass by Value

Pass by Reference vs. Pass by Value Pass by Reference vs. Pass by Value Most methods are passed arguments when they are called. An argument may be a constant or a varable. For example, n the expresson Math.sqrt(33) the constant 33 s passed

More information

Cache Performance 3/28/17. Agenda. Cache Abstraction and Metrics. Direct-Mapped Cache: Placement and Access

Cache Performance 3/28/17. Agenda. Cache Abstraction and Metrics. Direct-Mapped Cache: Placement and Access Agenda Cache Performance Samra Khan March 28, 217 Revew from last lecture Cache access Assocatvty Replacement Cache Performance Cache Abstracton and Metrcs Address Tag Store (s the address n the cache?

More information

The AVL Balance Condition. CSE 326: Data Structures. AVL Trees. The AVL Tree Data Structure. Is this an AVL Tree? Height of an AVL Tree

The AVL Balance Condition. CSE 326: Data Structures. AVL Trees. The AVL Tree Data Structure. Is this an AVL Tree? Height of an AVL Tree CSE : Data Structures AL Trees Neva Cernavsy Summer Te AL Balance Condton AL balance property: Left and rgt subtrees of every node ave egts dfferng by at most Ensures small dept ll prove ts by sowng tat

More information

Tsinghua University at TAC 2009: Summarizing Multi-documents by Information Distance

Tsinghua University at TAC 2009: Summarizing Multi-documents by Information Distance Tsnghua Unversty at TAC 2009: Summarzng Mult-documents by Informaton Dstance Chong Long, Mnle Huang, Xaoyan Zhu State Key Laboratory of Intellgent Technology and Systems, Tsnghua Natonal Laboratory for

More information

Module Management Tool in Software Development Organizations

Module Management Tool in Software Development Organizations Journal of Computer Scence (5): 8-, 7 ISSN 59-66 7 Scence Publcatons Management Tool n Software Development Organzatons Ahmad A. Al-Rababah and Mohammad A. Al-Rababah Faculty of IT, Al-Ahlyyah Amman Unversty,

More information

Machine Learning. Topic 6: Clustering

Machine Learning. Topic 6: Clustering Machne Learnng Topc 6: lusterng lusterng Groupng data nto (hopefully useful) sets. Thngs on the left Thngs on the rght Applcatons of lusterng Hypothess Generaton lusters mght suggest natural groups. Hypothess

More information

Summarizing Data using Bottom-k Sketches

Summarizing Data using Bottom-k Sketches Summarzng Data usng Bottom-k Sketches Edth Cohen AT&T Labs Research 8 Park Avenue Florham Park, NJ 7932, USA edth@research.att.com Ham Kaplan School of Computer Scence Tel Avv Unversty Tel Avv, Israel

More information

A New Approach For the Ranking of Fuzzy Sets With Different Heights

A New Approach For the Ranking of Fuzzy Sets With Different Heights New pproach For the ankng of Fuzzy Sets Wth Dfferent Heghts Pushpnder Sngh School of Mathematcs Computer pplcatons Thapar Unversty, Patala-7 00 Inda pushpndersnl@gmalcom STCT ankng of fuzzy sets plays

More information

A Fast Visual Tracking Algorithm Based on Circle Pixels Matching

A Fast Visual Tracking Algorithm Based on Circle Pixels Matching A Fast Vsual Trackng Algorthm Based on Crcle Pxels Matchng Zhqang Hou hou_zhq@sohu.com Chongzhao Han czhan@mal.xjtu.edu.cn Ln Zheng Abstract: A fast vsual trackng algorthm based on crcle pxels matchng

More information

Smoothing Spline ANOVA for variable screening

Smoothing Spline ANOVA for variable screening Smoothng Splne ANOVA for varable screenng a useful tool for metamodels tranng and mult-objectve optmzaton L. Rcco, E. Rgon, A. Turco Outlne RSM Introducton Possble couplng Test case MOO MOO wth Game Theory

More information

On the Efficiency of Swap-Based Clustering

On the Efficiency of Swap-Based Clustering On the Effcency of Swap-Based Clusterng Pas Fränt and Oll Vrmaok Department of Computer Scence, Unversty of Joensuu, Fnland {frant, ovrma}@cs.oensuu.f Abstract. Random swap-based clusterng s very smple

More information

Classifier Selection Based on Data Complexity Measures *

Classifier Selection Based on Data Complexity Measures * Classfer Selecton Based on Data Complexty Measures * Edth Hernández-Reyes, J.A. Carrasco-Ochoa, and J.Fco. Martínez-Trndad Natonal Insttute for Astrophyscs, Optcs and Electroncs, Lus Enrque Erro No.1 Sta.

More information

A Geometric Approach for Multi-Degree Spline

A Geometric Approach for Multi-Degree Spline L X, Huang ZJ, Lu Z. A geometrc approach for mult-degree splne. JOURNAL OF COMPUTER SCIENCE AND TECHNOLOGY 27(4): 84 850 July 202. DOI 0.007/s390-02-268-2 A Geometrc Approach for Mult-Degree Splne Xn L

More information

Angle-Independent 3D Reconstruction. Ji Zhang Mireille Boutin Daniel Aliaga

Angle-Independent 3D Reconstruction. Ji Zhang Mireille Boutin Daniel Aliaga Angle-Independent 3D Reconstructon J Zhang Mrelle Boutn Danel Alaga Goal: Structure from Moton To reconstruct the 3D geometry of a scene from a set of pctures (e.g. a move of the scene pont reconstructon

More information

Harvard University CS 101 Fall 2005, Shimon Schocken. Assembler. Elements of Computing Systems 1 Assembler (Ch. 6)

Harvard University CS 101 Fall 2005, Shimon Schocken. Assembler. Elements of Computing Systems 1 Assembler (Ch. 6) Harvard Unversty CS 101 Fall 2005, Shmon Schocken Assembler Elements of Computng Systems 1 Assembler (Ch. 6) Why care about assemblers? Because Assemblers employ some nfty trcks Assemblers are the frst

More information

2D Raster Graphics. Integer grid Sequential (left-right, top-down) scan. Computer Graphics

2D Raster Graphics. Integer grid Sequential (left-right, top-down) scan. Computer Graphics 2D Graphcs 2D Raster Graphcs Integer grd Sequental (left-rght, top-down scan j Lne drawng A ver mportant operaton used frequentl, block dagrams, bar charts, engneerng drawng, archtecture plans, etc. curves

More information

9. BASIC programming: Control and Repetition

9. BASIC programming: Control and Repetition Am: In ths lesson, you wll learn: H. 9. BASIC programmng: Control and Repetton Scenaro: Moz s showng how some nterestng patterns can be generated usng math. Jyot [after seeng the nterestng graphcs]: Usng

More information

Notes on Organizing Java Code: Packages, Visibility, and Scope

Notes on Organizing Java Code: Packages, Visibility, and Scope Notes on Organzng Java Code: Packages, Vsblty, and Scope CS 112 Wayne Snyder Java programmng n large measure s a process of defnng enttes (.e., packages, classes, methods, or felds) by name and then usng

More information