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 deal for ths purpose. We need a more precse notaton to present algorthms that s not subject to dfferng nterpretatons. At the other extreme formal programmng languages (such as C, C++, Java, Perl, ADA, Python, etc.) are very nflexble n ther syntax, and requre much attenton to detal. hese detals may be rrelevant n the ntal desgn phases of an algorthm. Instead we use an nformal and flexble language called pseudo-code whch uses Englsh language constructs and conventons modeled to look lke commands avalable n most computer languages. Detaled & Exact Expressve & Abstract Computer Languages Pseudo-Code Natural Languages Pseudo-code s a language n whch all necessary operatons can be expressed, but whch s ndependent of any computer language, or of any computer for that matter. Sequental Operatons are of three basc knds: computaton, nput, and output. he nstructon for performng a calculaton and storng the result s wrtten as varable expresson hs nstructon tells the computng agent to evaluate the expresson on the rght and assgn ts value to the varable on the left. he left arrow n ths context s called the assgnment operator. Example c a + b + carry Example x b+ b 4ac a Unless otherwse stated, we wll assume that the computng agent s at least as capable as any scentfc calculator, so that the above expressons are consdered prmtve operatons. 5
Input and output operatons allow the computng agent to receve data values from, and send results to the outsde world, whch we also call the user. Computng Agent Input Output Outsde World he operatons used for nput and output are get and prnt respectvely. Example get x Example prnt x Example prnt x + 5 get varable prnt varable prnt expresson ext to be prnted wll be placed n sngle quotes. Example prnt error: dvson by zero Example prnt the value of x s: x and the value of y s: y An algorthm whch uses only sequental operatons s sometmes called a straght lne algorthm. Example ) get a, b, c, d ) sum a + b+ c+ d ) average sum / 4 4) prnt average What does ths algorthm do? Condtonal operatons (also called branchng operatons) are expressed usng the f statement or the f-else statement. he f statement s wrtten as f condton do somethng do somethng do somethng do somethng 6
In ths structure condton stands for a logcal (or Boolean) expresson,.e. an expresson that can be evaluated as true or false. If condton s true, then the ndented lnes are executed, followed by the unndented lnes. If on the other hand condton s false, then the ndented lnes are skpped, and executon pcks up at the next unndented lne. he ndented commands are known as the true branch of the condtonal. An f statement may also come wth an accompanyng else clause. f condton do somethng do somethng else do somethng do somethng do somethng If condton s true, then the frst group of ndented nstructons s executed, and the second group s skpped, followed by the next unndented nstructon. If condton s false, then the frst group s skpped, and the second group of ndented nstructons s executed, followed by the next unndented nstructon. In ths structure the second group of ndented nstructons s known as the false branch of the condtonal, whle the frst group s know as the true branch, as before. Example What does the followng algorthm do? ) get a, b ) f b = 0 ) prnt 'Error: dvson by zero' 4) else 5) quotent a / b 6) prnt quotent 7) stop Iteratve operatons (also called loops) wll be expressed n pseudo-code through three commands: whle, do-whle, and for. whle condton do somethng do somethng do somethng Frst condton s tested, and f found to be true, the ndented lnes (called the loop body) s executed. he condton s tested agan, and f found to be true, the loop body s executed agan. hs process contnues untl the condton s found to be false, n whch case executon pcks up at the next unndented lne. he whle loop condton s sometmes called a loop repetton condton snce the loop body repeats only so long as ths logcal expresson s true. 7
Example What does the followng algorthm do? ) response 'yes' ) whle response = 'yes' ) get a, b 4) f b = 0 5) prnt 'Error: dvson by zero' 6) else 7) prnt a / b 8) prnt 'Do you wsh to contnue?' 9) get response 0) stop he do-whle loop structure puts the loop repetton condton after the loop body. do do somethng do somethng whle condton do somethng Frst the loop body, whch conssts of just those lnes that are ndented, s executed. hen the condton s tested, and f found to be true, the loop body s repeated. We contnue executng the loop body untl condton becomes false, then executon pcks up at the next unndented lne after whle. he loop repetton condton s called a post test condton n ths case snce t s tested after the frst executon of the loop body. he condton n the whle loop on the other hand s called a pre test condton, snce t s tested before the frst executon of the loop body. Example Notce that the loop body n ths example s dentcal to the one n the precedng example. ) do ) get a, b ) f b = 0 4) prnt "Error: dvson by zero' 5) else 6) prnt a / b 7) prnt 'Do you wsh to contnue?' 8) get response 9) whle response = 'yes' 0) stop We often encounter whle loops wth the followng general structure Intalze the loop control varable whle n est the loop repetton condton do somethng wth + Increment the loop control varable 8
We can do these three steps, ntalze loop control varable, test loop repetton condton, and ncrement loop control varable, more succnctly wth the for loop structure below, whch s equvalent to the precedng whle loop. for to n do somethng wth Example Here are two equvalent algorthms, one uses a whle loop, and the other uses an equvalent for loop. A trace of both algorthms would be dentcal. ) ) whle 5 ) prnt 4) + 5) stop ) for to 5 ) prnt ) stop It has been proved that one can represent any vald algorthm wth the operatons so far descrbed. We now consder some well known algorthms whch perform certan basc tasks n computer scence. Example Consder the problem of lookng up a name and correspondng telephone number n a drectory NAE Names Numbers N N N N N n n We assume that the names are n no partcular order (.e. not necessarly n alphabetcal order) so that we must look at each name n successon. If we fnd a name N whch matches our target NAE, we return the correspondng number. If no effect. We call ths algorthm Sequental Search. N s a match, we prnt a message to that Input: n (the number of names n the lst), N, L, N and n, L,n (the lst of names and correspondng telephone numbers), and NAE (the target name we are searchng for.) Output: the telephone number for whch NAE = N, or f no such name exsts, prnt a message to the user. 9
Sequental Search.) Get n, N, K, N n,, K, n, NAE from the user.).) found false 4.) whle n and not found 5.) f N = NAE 6.) found true 7.) prnt 8.) else 9.) + 0.) f not found.) prnt sorry NAE not n drectory.) stop he varable found s called a logcal varable or Boolean varable (named after the Logcan George Boole). It stores one of the two logcal values true or false. A logcal expresson s an expresson whch evaluates to one of these two values. In order to understand how these expressons are evaluated, we must frst defne the logcal operators and, or, and not. A proposton s a statement or asserton whch can (at least n prncple) be evaluated as beng ether true or false. For nstance today s Wednesday and 6< 7 are propostons, whle hello and x < 7 are not propostons. Let A and B be propostonal varables,.e. varables whch stand for unspecfed propostons. We can form the compound propostons A and B, A or B, and not A, usng the operators and, or, and not, whch are defned as follows. A B A and B F F F F F F F In ths truth table, stands for true and F stands for false. In words, A and B s true only n the case when both operands are true, and s false n every other case. A B A or B F F F F F Agan n words, A or B s false only n the case when both operands are false, and s true n every other case. A not A F F hus not A just reverses the logcal value of ts operand A. he operators and and not have the same meanngs that any speaker of Englsh would expect. However there s some ambguty 0
n the Englsh language concernng the word or. he above truth table for or defnes an operaton whch s more properly called nclusve or. It asserts that ether A, or B, or possbly both are true here s another meanng of the word or n the Englsh language called exclusve or, abbrevated exor. hs operaton s defned by the followng truth table. A B A exor B F F F F F F hus A exor B asserts that ether A, or B, but not both are true. Unfortunately for speakers of Englsh, there s no such word as exor, and both meanngs are denoted by the word or. he lstner s expected to gather the meanng from the context. Example A man wth a gun walks up to you and says your money or your lfe. Whch or do you hope he s usng? Fortunately n athematcs and Computer Scence there s no ambguty. Whenever you see the word or used n a ath textbook, t means nclusve or. If we ever mean exclusve or, we explctly wrte exor (or perhaps some other symbol). Now we can see exactly how the logcal expressons on lnes 4 and 0 or Sequental Search wll be evaluated. here are many other examples of searchng problems where the data to be searched s n no partcular order. he algorthmc soluton s essentally the same as that of the phone book example,.e. step through the data from begnnng to end untl the target data tem s found. It s conceptually very useful and elegant to consder all these examples as beng dfferent nstances of the same problem, all solvable by the same algorthm. Snce everythng n Computer Scence s ultmately represent able by numbers, we can present ths Generalzed Sequental Search algorthm as a search of an unsorted lst of numbers for some target number. Input: n (the number of numbers n the lst), a,,an (the number to search for.) Output: he frst ndex such that Sequental Search.) Get n, a, K, an, target from the user.).) found false 4.) whle n and not found 5.) f a = target 6.) found true 7.) else 8.) + 9.) f not found 0.) 0.) prnt.) stop L (the lst of numbers tself), and target target = a, or 0 f no such ndex exsts.
Example race ths algorthm on the nput: n = 5, target =, and the lst, -,, 5,. Exercse odfy ths algorthm to fnd the last (.e. rghtmost) occurrence of the target. How can we modfy t to fnd the nd, or 5 th, or j th occurrence of the target? How can we modfy t to prnt the number of occurrences of the target? Another common problem n processng a lst of numbers s to fnd the largest or smallest number n the lst. he followng algorthm, called Fnd Largest, solves ths problem. Input: n (the number of numbers), and a, L,an (the lst of numbers, whch we assume to be dstnct). Output: he largest value n the lst, together wth the poston (.e. the ndex ) where t s located. Fnd Largest.) max a (max s the largest value seen so far).) j (j s the ndex of the largest value seen so far).) ( s the ndex of the element we are presently lookng at) 4.) whle n 5.) f a > max 6.) max a 7.) j 8.) + 9.) prnt max, j 0.) stop Example race ths algorthm on the lst,, -7, 5,,, 0. Exercse What happens f we run Fnd Largest on a lst whose elements are not dstnct? ry t on the lst,, 0, 0,, 5, 0. How can t be modfed to fnd all occurrences of the maxmum? How can t be modfed to fnd the mnmum? Exercse Assume that addton of ntegers s a prmtve operaton for the computng agent, but that multplcaton of ntegers s not. Wrte an algorthm whch takes as nput two (non-negatve) ntegers a and b, and prnts out ther product a b. Obvously one cannot wrte prnt a b snce we are assumng here that multplcaton s not prmtve. he problem s to defne multplcaton algorthmcally n terms of repeated addton, as follows..) get a, b.) product 0.) 4.) whle b 5.) product product+ a 6.) + 7.) prnt product 8.) stop
hs algorthm could be wrtten a lttle more succnctly usng a for loop..) get a, b.) product 0.) for to b 4.) product product+ a 5.) prnt product 8.) stop Exercse Now assume that multplcaton s a prmtve operaton for the computng agent, but that exponentaton (.e. rasng a number to a power) s not. Wrte an algorthm whch takes as b nput two (non-negatve) ntegers a and b, then prnts out the value a. Agan t s obvous that b statement prnt a s not a vald operaton. he problem s to defne exponentaton n terms of repeated multplcaton. A classcal problem n Computer Scence s Pattern atchng. here are many versons of ths problem dealng wth patterns n graphcs, sound, pctures, and other types of data. We wll consder a smple form of ths problem: fndng patterns n text data. ore precsely, gven n characters of text KKKKKKKKK n and gven a pattern of m characters, where m n P P P KK P m fnd every occurrence of the pattern wthn the text,.e. fnd each ndex poston n the text at whch the pattern begns. Example n = 8, m= text: to be or not to be pattern: be answer: 4, 7 Example n = 0, m= text: xxxaaaaaxx pattern: aaa answer: 4, 5, 6 Notce that f m =,.e. f the pattern has just one character n t, then ths problem s not essentally dfferent from the searchng problem. We may expect that our algorthm wll show some smlarty to Sequental Search. Our soluton wll be to smply compare the pattern, one character at tme, to m contguous text characters at every possble startng locaton wthn the text. We start by comparng P to, and f they match compare P to, and f they match compare P to, etc. We contnue n ths manner untl reach the end of the pattern and thus establsh that the pattern matches the text at poston, or untl we fnd two characters whch don t match, ndcatng a msmatch at poston. We then slde the pattern over one poston n
the text and compare P to, then P to, etc. as before untl we ether establsh a match or a msmatch at poston n the text. Every tme a match occurs, we prnt out the ndex wthn the text at whch the pattern and text matched. Example n = 7, m= check for match at poston = 4 5 6 7 P P P slde over = 4 5 6 7 P P P = 4 5 6 7 P P P = 4 4 5 6 7 P P P = 5 4 5 6 7 P P P In ths case we see that the possble answers,.e. the set of possble ndces at whch a match can occur, are = to = 5, snce to slde the pattern over one more tme would cause t to fall off the end of the text. In general the ndces to be tested range from = to = n m+. Input: Integers n and m satsfyng m n, the text KKKn to be searched, and the pattern P P P KPm to search for. Output: All ndces such that P P P KPm matches + + K + m. Pattern atch.).) whle n m+.) j 4.) match true 5.) whle j m and match 6.) f P j + j 7.) match false 8.) else 9.) j j+ 0.) f match.) prnt match found at poston.) +.) stop 4
Exercse race ths algorthm on some smple examples lke to be or not to be or xxxaaaaaxx above. Search for varous patterns wthn these texts. Exercse How can ths algorthm be used to fnd words rather than patterns? For nstance consder the text hand the band to randy and I, and search for the pattern and. he answers wll be postons,, 8, and. However the word and appears only once, at poston. How can we use ths algorthm to fnd only the word and and not all occurrences of the pattern and wthn other words? 5