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 (nt n) f (n == ) return ; return n*fact(n-); Shorter, smpler to understand Uses fewer varables Machne has to do more work runnng ths one! Course Materal SD, SB, PSK, NSN, DK, TAG CS&E, IIT M Tree Recurson When the recursve call s made more than once nsde the functon. For example, Fbonacc numbers fb(n) = fb(n-) + fb(n-) f n > = n f n s 0 or Ackerman s functon One of the fastest growng functons A(m, n) = n + f m = 0 = A(m-, ) f n = 0 = A(m-, A(m, n-)) otherwse 3 Fbonacc Numbers fb(4) fb(5) fb(3) fb(3) fb() fb() fb() 0 0 fb() fb() fb() fb(0) fb() fb(0) fb() 0 fb(0) 3 5 nt fb(nt n) /* n >= 0 */ f (n == 0) return 0; f (n == ) return ; return fb(n - ) + fb(n - ); 4 Fbonacc Numbers Lnear Recurson nt fb(nt n) return fb_aux( n,, 0) nt fb_aux(nt n, nt next, nt result) f (n == 0) return result; return fb_aux(n -, next + result, next); Computaton beng done n the recursve call f: 0,,,, 3, 5, 8 n: 0,,, 3, 4, 5, 6 fb(5) fb_aux(5,, 0) fb_aux(4,, ) fb_aux(3,, ) fb_aux(, 3, ) fb_aux(, 5, 3) fb_aux(0, 8, 5) 5 Who Was Fbonacc? The "greatest European mathematcan of the mddle ages" Hs full name was Leonardo of Psa Born n Psa (Italy), about 75 AD Was one of the frst people to ntroduce the Hndu-Arabc number system nto Europe These are the nne fgures of the Indans: 9 8 7 6 5 4 3. Wth these nne fgures, and wth ths sgn 0 whch n Arabc s called zephrum, any number can be wrtten. Part of hs book Lber abac Best known for a smple seres of numbers, later named the Fbonacc numbers n hs honour. 6
Fbonacc Numbers The seres begns wth 0 and. After that, use the smple rule: Add the last two numbers to get the next,, 3, 5, 8, 3,, 34, 55, 89, 44, 33, 377, 60, 987,... Suppose a newly-born par of rabbts, one male, one female, are put n a feld. Rabbts are able to mate at the age of one month so that at the end of ts second month a female can produce another par of rabbts. Suppose that our rabbts never de and that the female always produces one new par (one male, one female) every month from the second month on. The puzzle that Fbonacc posed was... How many pars wll there be n one year? Rabbt Pars How many pars wll there be n one year?. At the end of the frst month, they mate, but there s stll one only par.. At the end of the second month the female produces a new par, so now there are pars of rabbts n the feld. 3. At the end of the thrd month, the orgnal female produces a second par, makng 3 pars n all n the feld. 4. At the end of the fourth month, the orgnal female has produced yet another new par, the female born two months ago produces her frst par also, makng 5 pars. In general, magne that there are x n pars of rabbts after n months. The number of pars n month n+ wll be x n (n ths problem, rabbts never de) plus the number of new pars born. But new pars are only born to pars at least month old, so there wll be x n- new pars. x n+ = x n + x n- 7 8 Rabbt Pars An Erratc Sequence In Godel, Escher, Bach: An Eternal Golden Brad, D. R. Hofstadter ntroduces several recurrences whch gve rse to partcularly ntrgung nteger sequences. Hofstadter's Q sequence (also known as Meta-Fbonacc sequence) Q() = Q() = Q(n) = Q(n - Q(n - )) + Q(n - Q(n - )) for n > Each term of the sequence s the sum of two precedng terms, but (n contrast to the Fbonacc sequence) not necessarly the two last terms. The sequence Q(n) shows an erratc behavour,,, 3, 4, 5, 5, 6, 6, 6, 8, 8, 8, 0, 9, 0, gets more and more erratc 9 0 Whch s the Bggest? Gven three numbers a, b, and c, fnd the bggest amongst them. Defne a varable max to store the value. f (a > b && a > c) max = a; else f (b > c) max = b; else max = c; Other smlar code also works Method works for array elements as well A(), A(), A(3) But what f the array s large? Ths approach s not feasble Hghest Marks Gven an array marks[00], fnd the hghest marks n the class. max = marks[0]; /* for the tme beng */ for (=; <00; ++) f (marks[] > max) max = marks[]; /* update f bgger */
More Statstcs Gven an array marks[00], fnd the hghest, lowest and average marks n the class. max = marks[0]; /* for the tme beng */ mn = marks[0]; sum = marks[0]; for (=; <00; ++) f (marks[] > max) max = marks[]; f (marks[] < mn) mn = marks[]; sum += marks[]; average = sum/00; /*assumng floatng pont*/ 3 Exchangng Values Exchange the values of varables (a and b) a = b; INCORRECT b = a; Value of a s lost! Need to use a temporary varable temp = a; /* save the value of a */ a = b; b = temp; 4 Exchangng Values wthout temp What about the followng method that does not use an extra varable? a = a+b; b = a - b; a = a - b; Exercse: Does t work? What are the lmtatons? Do you need to be careful about somethng? Swap Array Elements vod swap (nt array[ ], nt, nt j) nt temp; temp = array[]; array[] = array[j]; array[j] = temp; 5 6 Where s the Hghest Number? Gven an array of n elements, a startng ndex, fnd out where the largest element les beyond and ncludng. nt MaxIndex (nt array[ ], nt start, nt arraysze) nt = start; nt ndex = start; nt max = array[]; for ( ; < arraysze; ++) /* observe null statement */ f (array[] > max) max = array[]; ndex = ; return ndex; 7 Sortng an Array of Numbers Problem: Arrange the marks n decreasng order startng wth the maxmum. One approach Fnd the maxmum value n marks[0] marks[99] Remember the ndex where t occurred Exchange (values of) marks[0] and marks[] Fnd the maxmum value n marks[] to marks[99] exchange marks[] and marks[]... do ths tll marks[98] 8 3
Selecton Sort for (=0, <= n -, ++) swap (marks,, MaxIndex(marks,, n)); or more legbly swap s an functon that passes array by reference. The last element need not be tested for (=0, <= n -, ++) nt maxindex = MaxIndex(marks,, n); f (maxindex!= ) swap(marks,, maxindex); Selecton Sort as a Functon vod selectsort(nt array[ ], nt sze) nt maxindex, ; for ( = 0; <= sze ; ++) maxindex = MaxIndex(array,, sze) f (maxindex!= ) swap(array,, maxindex); 9 0 An Example 0 3 4 5 6 7 7 5 8 3 6 4 0 maxindex 4 8 7 5 3 6 4 8 7 5 3 6 4 6 8 7 6 5 3 4 3 3 8 7 6 5 3 4 4 7 8 7 6 5 4 3 5 5 Complexty of Selecton Sort 0 3 4 5 6 7 8 9 n=0 =0 n-=9 comparsons = n-=8 comparsons = n-3=7 comparsons =3 n-4=6 comparsons =4 n-5=5 comparsons =5 n-6=4 comparsons =6 n-7=3 comparsons =7 n-8= comparsons =8 n-9= comparson (n-)*n n / Complexty of Selecton Sort In each teraton, MaxIndex fnds the maxmum element Complexty of MaxIndex s order n à O(n) Can we do ths faster? Yes, by arrangng the numbers n a data structure called a MaxHeap MaxHeap can extract max element n O(log(n)) Algorthm Heapsort complexty O(n log(n)) Selecton sort does (n-) passes of reducng length (average length n/) Complexty (n-)*n/ à O(n /) à O(n ) Inserton Sort Inserton sort also scans the array from left to rght When t looks at the th element, t has elements up tll (-) sorted sorted It moves the th element to ts correct place by shftng the smaller elements to the rght 3 4 4
InsertMax Functon sorted Complexty of InsertMax sorted vod InsertMax (nt array[ ], nt ndex) nt = ndex; nt valueatindex = array[ndex]; whle( > 0 && array[-] < valueatindex) array[] = array[-]; /*shft rght*/ --; array[] = valueatindex; If the th element s n sorted order (smaller than the sorted set), no shft s done The maxmum number of shfts s (-) Complexty worst case O() best case O() constant tme 5 6 Inserton Sort Functon vod InsertonSort(nt array[ ], nt sze) nt ; for( = ; <= sze ; ++) InsertMax(array[ ], ); Complexty best case O(n) worst case O(n /) = O(n ) An Example 0 3 4 5 6 7 7 5 8 3 6 4 # of comp 7 5 8 3 6 4 7 5 8 3 6 4 3 3 7 5 8 3 6 4 4 4 8 7 5 3 6 4 5 3 7 8 7 5 3 6 4 6 5 8 Selecton Vs Inserton Sort Scannng from left to rght Selecton sort Swaps the th element wth the largest unsorted element Inserton sort Inserts the th element nto ts proper place 9 Selecton Vs Inserton Selecton sort always does the same number of computatons rrespectve of the nput array Inserton sort does less work f the elements are partally sorted when the th element s n place, t does not have to shft any elements constant tme If the nput s already sorted, Inserton sort merely scans the array left to rght confrmng that t s sorted On the average, Inserton sort performs better than Selecton sort 30 5
Inserton Sort Sorted Input Inserton Sort Reverse Sorted Input The best case complexty of InsertMax s O(). In each pass, functon InsertMax makes one comparson. Area n (n- lnes of unt length per area) The worst case complexty of InsertMax s O(n). In each pass, functon InsertMax has to move the element to the leftmost poston. Area n (n- lnes of average length per area as n/) 3 3 Inserton Sort Random Input The worst case complexty of Inserton sort s O(n ). In each pass, functon InsertMax has to move the element to the leftmost poston. Area < n / Exercse for ths Week Gven an array of strngs, called names, and an array of marks, called marks, such that marks[] contans the marks of names[] sort the two lsts n decreasng order of marks sort the two lsts n alphabetc order of names fgure out how to compare two names to decde whch comes frst. 33 34 6