0% found this document useful (0 votes)
39 views

Chapter 11

Uploaded by

Adnan Saleem
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
39 views

Chapter 11

Uploaded by

Adnan Saleem
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 30
Chapter 11 Part 2 Fundamental Problem-Solving and Programming Skills Algorithm Design and Problem-Solving By the end of this chapter you should be able to: show understanding that an algorithms a solution toa problem expressed as a sequence of defined steps Use suitable identifier for the representation of data used by a problem and summarise identifiers using an identifier table show understanding that many algorithms are expressed using the four basic constructs of assignment, sequence, selection and repetition show understanding that simple algorithms consist of input, process, output at various stages document a simple algorithm using: structured English, pseudocode, program flowchart oe derive pseudocode or a program flowchart from a structured English description of a problem derive pseudocode from a given program flowchart show an appreciation of why logic statements are used to define parts of an algorithm solution se logic statements to define parts of an algorithm solution Use the technical terms associated with arrays including, Upper and lower bound select a suitable data structure (10 oF 20 array) to use for a given task ‘rite algorithms to process array data including sorting using a bubble sort and searching using a linear search. 11.01 What is an algorithm? (oc Algorithm: 2 sequence of steps that can be carried out to perform a task We use algorithms in everyday life. fyou need to change a wheel on a car, you might need to follow instructions (the algorithm) from a manual: Take a spanner and loosen the wheel nuts. Position a jackin an appropriate place. Ralse the car. Take off the wheel nuts and the wheel. Lift replacement wheel into position. Replace wheel nuts and tighten by hand. Lower the car. eran ewne Fully tighten wheel nuts, This might sound all very straightforward. However, if the instructions are not followed in the correct logical sequence, the process might become much more difficult or even impossible. For example, if you tried to do Step 1 after Step 3, the wheel may spin and you can't loosen the wheel nuts. You can't do Step 4 before Step 3, If you want to bake a cake, you follow a recipe: 1. Measure the following ingredients: 200g sugar, 200g butter, 4 eggs, 200g flour, 2 teaspoons baking powder and 2 tablespoons of milk 2. Mixthe ingredients together in a large bowl, until the consistency of the mixture is smooth, Pour the mixture into a cake tn, Bake in the oven at 190° C for 20 minutes. Check itis fully cooked. 6 Turn cake out ofthe tin and cool on a wire rack wee The recipe is an algorithm. The ingredients are the input and the cake is the output. The process is mixing the ingredients and cooking the mixture in the oven metimes a step might need breaking down into smaller steps. For example Step 2.can be more detailed. 2.1 Beat the sugar and butter together until fluffy. 2.2 Add the eggs, one ata time, mixing constantly 2.3 Sieve the flourand baking p 2.4 Add milk and mixto give a creamy consistency. der and stir slowly into the egg mixture, Chapter 11: Algorithm Desi aC id Sometimes there might be diferent steps depending on some other conditions. For example, consider how to get from one place to another using the map of the London Underground system in Figure 11.01. Precadily — Vietaria = tubiee Figure 11.01 Underground map of London, UK To travel from King's Cross St. Pancras to Westminster, we consider two routes: + Route Take the Victoria Line to Green Park stations}; then take the Jubilee Line to E Westminster (1 station). + Route B: Take the Piccadilly Line to Green Park (6 stations}; then take the Jubilee Line to Westminster (1 station). Route looks lke the best route f there are engineering works on the Victoria Line and trains are delayed, Route B might turn out to be the quicker route. The directions on how to get from King’s Cross St. Pancras to Westminster can be written as: IF there are engineering works on the Victoria Line THEN Take the Piccadilly Line to Green Park (6 stations) Take the Jubilee Line to Westminster ( station) ELSE Take the Victoria Line to Green Park (4 stations) Take the Jubilee Line to Westminster (1 station) TASK:1.01 Wirite the steps to be followed to: + makea sandwich + walk from your school/college to the nearest shop + logonto your computer. Many problems have more than one solution. Sometimes itis a personal preference which solution to choose. Sometimes one solution will be better than another. Cambridge Internati al AS and A level Computer Science 11.02 Expressing algorithms mP Computer scientists are interested in finding good solutions. A good solution gives the correct results, takes up aslittle computer memory as possible and executes as fat as possible. The solution should be concise, elegant and easy to understand. In computer science, when we design a solution to a problem we express the solution thea) angseq uence step rien REAR THEN ... THEM... ELSE... ELSE expe 30. ves REPEAT UNTIL A IS EQUAL TO B [REPEAT luwtin A= B (eo) wo yes PUT "Message" B HEOT TNPOT "Prompts" A INPUT "Prompt:" A [OUTPUT "Message" GUTPOT "Message" 5 Jourur B ia Table 11.01 Constructs for computing algorithms Dees ate In this book, algorithms and program code are typed using the courier font. 11.03 Variables When we input data for a process, individual values need to be stored in memory. We need to be able to refer to a specific memory location so that we can write statements of what to cdo with the value stored there. We refer to these named memory locations as variables. You can imagine these variables like boxes with name labels on them. When a value is input, itis stored in the box with the specified name (identifier) on it Ce Variable: storage location fora data value that has an identifier For example, the variable used to store a count of how many guesses have been made might be given the identifier Nunberofcuesses and the player's name might be stored in a variable called ThisPiayer, as shown in Figure 11.03 NumberotGuesses ‘ThisPlayer Figures (EBRD 7o make algorithms easier to understand, the naming of variable should reflect the variable’s use. This means often that more than one word is used as an identifier. The formatting convention used here is known aQ@AiMBlGABB. I makes an identiler easier to read 11.04 Assignments Assigning a value The following pseudocode storesthe value _The following pseudocode stores the that is input (for example 15) in a variable with value 1 in the variable with the identifier the identifier Number (see Figure 11.04(a)). NumberofGuesses (see Figure 11.04(b)). NumberofGuesses. Number (a) (o) Figure 11.04 Variables being assigned a value Updating a value ‘The following pseudocode takes the value stored in NumberofGuesses (see Figure 11.05 (a), ‘adds 1 to that value and then stores the new value back into the variable NumberOfGuesses (see Figure 11.05 (b, ae NunberOfGuesses > NumberofGuesses, @ (b) Figure 11.05 Updating the value ofa variable Copyinga value Values can be copied from one variable to another. The following pseudocode takes the value stored in value and copies it to value (Gee Figure 11.06) PP ae a a) {b) Figure 11.06 Copying the value of a variable The value in vatuei remains the same until it's assigned a different value. IF we want to swap the contents of two variables, we need to store one of the values in another variable temporarily, Otherwise the second value to be moved will be overwritten by the first value to be moved, ee ea DEN Reg In Figure 11.07(a), we copy the content from values into a temporary variable called Temp. ‘Then we copy the content from value2 into Valuer Figure 11.07(b)) Finally we can copy value from Temp into value2 (Figure 11.07\¢ ae Valuez valuel _ value valuez [C) Figure 11.07 Swapping the values of two variables Using pseudocode we writ Prircscun tas) Using input, output, assignment and sequence constructs The problem to be solved: Convert ad tance in milesand output the equivalent distance in km, Step 1: Write the problem asa series of structured English statement: INPUT number of miles Calculate number of km OUTPUT calculated result as kn needed, Step 2: Analyse the data values that 21 We need a variable to store the original distance in miles and a variable to store the resul | of multiplying the number of miles by 1.61. Itis helpful to construct an identifier table to identifier [Explanation wiles Distance as a whole number of miles | Kin The result from using the given | formula: Ken = Miles * 1.61 Table 11.02 Identifier table for miles to km conversion Cr eS eae ae ace Step 3 Provide more detail by drawing af hart or writing pseudocode. The detail given ina flowchart should be the same as the detail given in pseudocode. It should use the basic constructs listed in Table 11.01. Figure 11.08 represents our algorithm using a flowchart and the equivalent pseudocode. INPUT "Enter miles:" Miles Star} Xn 2 table listing the variable identifiers required forthe olution, with exolanations ‘TASK11.02 Consider the fallowing algorithm steps: 1. Inputa length in inches. 2. Caleulate the equivalent in centimetres. 3. Outputtthe result List the variables required in an identifier table. White pseudocode or draw flowchart for the algorithm, ert are CE UTE 11.05 Logic statements In Section 1.01, we looked at an algorithm with diferent steps depending on some other condition: IF there are engineering works on the Victoria Line THEN Take the Piccadilly Line to Green Park (6 stations) Take the Jubilee Line to Westminster (1 station) ELSE Take the Victoria Line to Green Park (4 stations) Take the Jubilee Line to Westminster (1 station) The selection construct in Table 11.01 uses a condition to follow either orthe second group of steps (see Figure 11.09) wR THEN ELSE statement (s)> ENDIF ne frst group of steps IF Figure 11.09 Structured English for the selection construct condition consists of atleast one logic proposition propositions use the relation ‘Operator [comparison Is equal to [isless than Is greater then Is less than or equal to Is greater then or equal to Is not equal to (See Chapter 4, Section 4,01). Logic (comparison) operators shown in Table 11.03. aly oly Table 11.03 Relational operators Conditions are either TRUE or FALSE. In pseudocode, we distinguish between the relational operator = (which tests for equality) and the assignment symbol = Apperson is classed as a child if they are under 13 and as an adult if they are over 19. If they are between 13 and 19 inclusive they are classed as teenagers, We can write these statements as logic statements: + IfAge<13 then personis a child + Age 19 then personis an adult + IfAge>=13 AND Age 19 then person is a teenager Chapter 11: Algorithm Design and Problem Solving TASK:1.03 ‘town hasa bus service where passengers under the age of 12 and over the age of 60do not need to pay a fare. Write the logic statements for fee fares. ‘Anumber guessing game follows different steps depending on certain conditions. Here's a description of the algorithm: +The player inputs a number to guess the secret number stored. + Ifthe guess was correct, output a congratulations message. + Ifthe number input was larger than the secret number, output message “secret numbers smaller” + Ifthe number input was smaller than the secret number, output message “secret number is greater". We can re-write the number-guessing game steps as an algorithm in-structured English: set value for secret number INPUT Guess IF Guess = 5% THEN OUTPUT "Well done. You have guessed the secret number" ELSE IF Guess > SecretNumber ‘THEN OUTPUT “secret number ie emaller" ELSE OUTPUT “secret number ie greater" sretNunber ENDIF ENDIF More complex conditions can be formed by using the logical operators AND, OR and NOT. For example, the number. guessing game might allow the player multiple guesses; i the player has not guessed the secret number after 10 guesses, a different message is output. IF Guess = SecretNunber ‘THEN OUTPUT "Well done. You have guessed the secret number" BLse Complex condition IP THEN OUTPUT "You still have not guessed the secret number" ELSE IF Guess > SecretMunber OUTPUT "The secret number io smaller" ELSE OUTPUT "The secret nunber is greater" ENDIF ENDIF ENDIF Cambridge International AS and A level Computer Science J WORKED EXAMPLE 11.02 Using selection constructs The problem to be solved ee number Ket as iputand output the largest number. There are several different methods (algorithms) to solve this problem, Here is one method: 1. Inputall three numbers at the beginning. 2. Store each of the input values in a separate variable {the identifiers a 1.04) 3. Compare the fist number with the second number and then compare: of these with the third number. hown in Table he bigger one 4. The bigger number of this second comparison is output, See Worked Example 11.03 for anather solution. Identifier Explanation fmumber — The first number to beinput Munbera The second number to be input Ranbers ‘The third numbertobeinput—_——_—| Table 11.04 Identifier table for biggest number problem The algorithm can be expressed inthe following pseudocode: INPUT Number 1 | INPUT Number? INPUT Nunber3 IF Number > Nunber2 THEN // Nuaber1 is bigger TF Munberl > Number? THEN OUTEUT Number OuTeUT munbex3 aNDrF ELSE // Number? is bigger IF Number2 > Numbers THEN OUTEUT Nunber2 ELSE OUTEUT Runber3 aNDIF ENDIF When an zr statement contains another 17 statement, we refer to these as nested TF statements, (ca Nested IF statements: concitional statements within conditional statements CO ere Ds ae Ce Question: 13.01 ‘What changes do you need to make to output the smallest number? Piitodscu ce Using selection constructs (alternative method) The problem to be solved: Take three numbers as input and output the largest number. Thisis an alternative method to Worked Example 11.02. 2 Input :hefirstrumber and storeitin Biggestsorar 2. Inputthe second number and compare it with the value in BiggestsoFar. 3 Ifthe second number i bigger, assign its value to Biggestsorar 4 Input the third number and compare it with the value in Biggest sorar 5 Ifthe third number is bigger, assign its value to BiggestSorar 6 Thevalue stored in siggestsorar is output. The identifiers required for this solution are shown in Table 11.05, BiggestsoFar ‘Stores the biggest number input so far exeiiunber The next number to be input ) ‘Table 11.05 Identifier table for the alternative solution to the biggest number problem The algorithm can be expressed inthe following pseudocode aeur mi IF Nextunber > Biggestsorar THEN > Biggestsorar € Nextmumber , ENDIF INPUT Nextiunber , IF NextNumber > BiggestSoFar , THEN Biggestsorar « Nextwumber ed , ’ or REESE Tee Fa chal fe Ao IRC inher TOT Tee Sete coral ) There ate several advantages of using the method in Worked Example 11.03 compared to the j method in Worked Example 11.02: + Only two variables are used. + The conditional statements are not nested and de not have an suse part. This makes them easier to understand, + This algorithm can be adapted more easily iffurther numbers are to be compared (see Worked Example 11.04 The disadvantage ofthe method in Worked Example 1.03 compared tothe method in Worked Example 11.02 is that there's more work involved with ths algorithm. the second number is bigger than the first number, the value of Biggest soFar has to be changed. IF the third number is bigger than the value in Biggest soFar then the value cf miggestSoFsr 5 to be changed again. Depending on the input values, this could result in two extra assignment instructions being carried out. 11.06 Loops Look at the pseudocode algorithm in Worked Example 11.03, The two ze statements are identical. To compare 10 numbers we would need to write this statement nine times, Moreover, ifthe problem changed to having to compare, for example, 100 numbers, our algorithm would become very tedious. if we use a repetition construct (a loop} we can avoid writing the same lines of pseudocode over and over again, Pid nu ain Repetition using »: ‘The problem to be solved: Take 10 numbers as input and output the largest number. We need one further variable to store a counter, so that we know when we have ‘compared 10 numbers. BiggestSoFar ‘Stores the biggest number input so far Wextitunber The next number to be input Counter ‘Stores how many numbers have been input so far Table 11.06 Identifier table for the biggest number problem using REPEAT. ..uwTIL, The algorithm can be expressed in the following pseudocode: INPUT BiggeatSorar INPUT NextNumber counter « Counter +1 IF NextNumber > BiggestSoFar THEN Biggestsorar © Ne fumber ENDIF OUTPUT Biggest SoFar Question: 11.02 What changes do you need to make to the algorithm in Worked Example 11.04: +. to.compare 100 numbers? + totake asa first input the number of numbers to be compared? There is another loop construct that does the counting for us: the FoR... .ANDFOR loop. Ciitodeeuk Repetition using 202... The problem to be solved: Take 10 numbers as input and output the largest number. We can use the same identifiers as in Worked Example 11.04, Note that the purpose of Counter has changed. Biggest soFar ‘Stores the biggest number input so far TextNunber The next number to be input Counter Counts the numberof times round the loop Table 11.07 Identifier table for biggest number problem using a FOR loop ‘The algorithm can be expressed in the following pseudocode: INPUT Biggestsorar ‘OUTPUT BiggestsoFar The first time round the loop, counter:is set to 2. The next time round the loop, Counter has automatically increased to 3, and so on. The last time round the loop, Counter has the value 10, APBETEAIB is 2 value used to terminate a sequence of values. The rogue value is ofthe same data type but outside the range of normal expected values, |) 2c toque ihe atte suet Pritodacua cn Repetition using a rogue value The problem to be solved: A sequence of non-zero numbers is terminated by 0. Take this sequence as input and output the largest number Note: n this example the rogue value chosen is. itis very important to choose a rogue value thats ofthe same data type but outside the range of normal expected values. For example, ‘the input might normally include O then a negative value, such as—1, might be chosen, Look at Worked Example 11.05. Instead of counting the numbers input, we need to check whether the number input is Oto terminate the loop. The identifiers are shown in Table 11.08. Biggestsorar Stores the biggest number input so far NextiNumber The next number to be input Table 11.08 Identifier table for biggest number problem using a rogue value Chapter 11: Algorithm Design and Problem Solving Coan en CEU EN Neeru cate aed ‘A possible pseudocode algorithm is: INPUT BiggestSorar " IP NextNumber > BiggestSoPar THEN BiggeetGorar « Nextiumber ENDIF OUTPUT BiggestsoFar | This algorithm works even ifthe sequence consists of only one non-zero input. However, twill not work ifthe only input is 0. In that case, we don't want to perform the statements hin the loop at all. We can use an alternative construct, the WHILE. ...NDWETZE loop. BiggeatsoFa a 2 sequence terninator not enccintered INPUT Nextwumber IF wextwunber > Biggestsorar Biggestsorar « NextMunber ENDIF eHILE OUTPUT BiggestSoPar Before we enter the loop we check whether we have a non-zero number. To make this work forthe first number, we storeit in Nexewunber and also in BiggestSoFar. I this first number is zero we don't follow the instructions within the loop. For a non-zero first number this algorithm has the same effect as the algorithm using REPEAT. UNTIL [iitorsnun kins Implementing the number-guessing game with a loop Consider the number guessing garne again, this time allowing repeated guesses: | | | 1. The ployer repeated) QIN uber siored 2th | 3 ifthe the player SecretNumber the player is given the message to input a smaller number IF Guess < SecretNumber THEN the player is given the message to input @ larger number ENDIF Pseudocode for the number-guessing game with <@RSReBHEESMISORD The above solution uses a post-condition (REPEAT. ..uwTIL) loop. An alternative solution uses a pre-condition (maxLi...ENDWETLE) loop Secretmumber « Random ror NumberOfcuesses WHI IP Guess > SecretMumber ‘THEN the player is given the message to input a smaller number IP Guess < Secretiunber THEN the player is given the message to input a larger munber mxpie Se. Munberofduesses + 1 Pris Uta Calculating running totals and averages The problem to be solved: Take 10 numbers as input and output the sum of these numbers and the average. I fRunningTotal [Stores the sum of the numbers input so far [counter How many numbers have been input )iexetiumber The next number input average The average of the numbers input ‘Table 11.10 Identifier table for running total and average algorithm Chapter 11: Algorithm Design and Problem Solving The following pseudocode gives a possible algorithm: Runningrotal — 0 INPUT NextNumber RunningTotal + RunningTotal + NextNumber (OUTPUT RunningTotal Average « RunningTotal / 10 OUTPUT Average Itis very important that the value stored in RunningTotal is initialised to zero before we start adding the numbers being input. TASK 11.04 ay the. gu in) cel aes so that the sequence ef numbersis | worken examPLe 1.09 | Using nested loops The problem tobe sce! I: QHED output gid made up entirely of the chosen symbol, with the number of rows matching the first number inputandthe numberof columns matching a E For example the three input values 3, 7 and & result in the output: easeeKs We need two variables to store the number of rows and the numberof columns. We also need a Variable to store the symbol We need a counter for the rows anda counter forthe columns. hunberofRows [Stores the number of rows of the grid fNanberofColumns Stores the number of columns of the grid Symbol [Stores the chosen character symbol fRowCounter [Counts the number of rows Columncounter [Counts the number of columns ‘Table 11.11 Identifier table for the nested loop example INPUT NunberotRows INPUT Nunberoscolumns INPUT symbol MunberofRows MunberofColumns OUTPUT symbol // without moving to next line ENDFOR OUTPUT Newline // move to the next line ENDFOR en eC CEG ke casera Each time round the outer loop (counting the number of rows) we complete the inner lo outputting a symbol for each count of the number of columns. This type of construct is called a nested loop. : SU aR Nested loop: oop containing anotherloop 11.07 Working with arrays reread Working with a one-dimensional array The problem ta be solved: Take seven numbers as input and store them for later use. We could u 70 number even separate variables. However, ifwe wanted our algorithm to work with , for example, then this would become very tedious. We can make use of a data structure, known asa ‘linear list’ or a one-dimensional (1D) array. This aray is given an identifier, for example myst, and each element within the array is referred to using this identifier and its position (index) within the array, For example, myLise(a] refers to the fourth elementin themyziat a ay. We can use a loop to acce pseudocode algorithm below ar produce the result in Figure 11.1. ss each array elementin turn. Ifthe numbers input to the 25, 34, 98, 7,41, 19 and 5 then the algorithm will ENDFOR Index MyList fa) 25 Q) 34 B) 98 (4 7 6 a (6 19 tm 5 Figure 11.10 myzie array populated by a loop eI ep ten eg a ac TASK11.05 Set up two arrays, one for your friends’ names and one for their ages as shown in Figure 11.11 Name Age fy | Mate ir 15 f| Fred a 16 | anna a 4 tani | —xenios (20 ” Figure 11.11 Arrays for names and ages Poeun Searching a 10 array The problem to be solved: Take a number as input. Search for this number in an existing 1D array of seven numbers (see Worked Example 11.10) Start at the first element of the array and check each element in turn until the search value is found or the end of the array is reache nybise Data structure (1D array) to store seven numbers Naxtndex The numberof elementsin the array SearchValue | The value to be searched for Found ‘TRUR ifthe value has been found ase ifthe value has not been found Index Index ofthe array element currently being processed Table 11.13 Identifier table for linear search algorithm ee OE Es Ke cee Found « _ wont or tne >= Wade Covey sYalve found &t Iocatons ted ‘The complex condition to the REPEAT. ..uwT11, loop allows us to exit the loop when, the search value is found, Using the variable round makes the algorithm easier to understand. Pound is initialised to razz before entering the loop and set to TRUE if the value is found, ifthe value is not in the array, the loop terminates when 1ndex is greater than or equal to Maxindex That means we have come to the end of the array. Note that using Maxcindexe in the logic statement to terminate the loop makes it much easier to adapt the algorithm when the array consists ofa different number of elements. The algorithm only needs to be changed in the first line, \ere Maxindex is given a value. |_| ok RRR Linear search: checking each element ofan arrayin tur fora required value TASK 11.06 Use the algorithm in Worked Example 11.11 asa design pattern to search fora friend's name and output their age. Contin The simplest way to red list of values is the following method: 1. Compare the first and second values. Ifthe first value is larger than the second value, swap them. 2. Compare the second and third values. IFthe second value is larger than the third value, swap them, 3. Compare the third and fourth values. swap them, he third value is larger than the fourth value, 4 Keep on comparing adjacent values, values in thelist have been processed. jpping them if necessary, until the lastt eee ef PE acu eard [Figure 1.12 shows what happens to the values as we work down the aay, flowing his | algorithm, rear] cre RET oe: aed Be baie Sain baie pair ear Si we Ll 23 25 = = = a rlC aa 3% % * eT es = : 7 = | | i # = 3 2 5 5 5 Figure 1.12 Swapping values working down the array ‘When we have completed the first pass through the entire array, the largest valueis in the correc poston atthe end ofthe aay. The other values may or may not bein the corect order ‘We need to work through the array again and again. After each pass through the array the next largest value will bein its correct position, as shown in Figure 1.13 ‘ater | [ After | [ after | [ after | [ afer | { after | passa | | pass2 | | pass | | passa | | passs | | passe | F 25 25 2s yr 7 T 5 E ” ” 7 35 19 3 98 7 ” w |{s 7 4a 19 al a 2 5 19 5 : | Zz Figure 11.13 States of the array after each pass In effect we perform a loop within a loop, a nested loot (ita ooo fom the act tha he The identifiers needed for the algorithm are listed in Table 11.13. 7 id MyList (1..71 | Data structure (1D array) to store seven numbers Maxtadex The number of elements in the array 2 The number of elements to compare in each pass i Counter for outer loop i Counter forinnertoop Temp Variable for temporary storage while swapping values Table 11.13 Identifier table for bubble sort algorithm, et sur CEU Nee Cela Mca arct The algorithm in pseudocode is nl « Maxtndex — 1 THEN ‘remp ~ MyList{3) MyList (j] < MyL MyList) + 1] ~ Temp ENDIF ENDFOR n“n-1/// this means the next time round the inner loop, we don't Uf look at the values already in the correct positions. ENDFOR The values to be sorted may already be in the correct order b been through allits iterations. Look a different from the first lst we sorted fe the outer loop has he list of values in Figure 11.44, itis only slightly =| a Figure 11.14 States of thelist after each pass After the third pass the values are alln the correct order but our algorithm will carry on with three further passes through the aay. This means we are making comparisons when 1no further comparisons need to be made. if we have gone through the whole of the inner loop (one pass) without swapping any values, we know that the array elements must be in the correct order. We can therefore replace the outer loop with a conditional loop fe can usea variable NoMoreswaps to store whether or nota swap has taken place during the current pass. We initialse the variable nomoreswaps to TRUE When we swap a pair of values we set Nottoreswaps to PRLSE. At the end of the pass through the array we can check whether a swap has taken plac ‘The identifier table for this improved algorithm is shown in Table 11.14 [Identifier Explanation Z MyList (1..71 Data structure (1D array) to store seven numbers. Maxtndex The number of elements in the array a The number of elements to compare in each pass Noworeswaps "TRUE when no swaps have occurred in current pass FaLse when a swap has occurred I Counter for innerloop Temp Variable for temporary storage while swapping values Table 11.14 Identifier table for improved bubble sort algorithm This improved algorithm in pseudocode is: n+ Maxtndex = 1 REPEAT WoMoreSwaps « TRUE FOR j+1T0n IF MyList{i] > MyListtj + ‘THEN ‘Temp + MyList{3) MyList ij] « mytisttj + a] MyList lj + 1] < Temp NoMoreswaps ~ FALSE ENDIF ENDFOR nen-2 UNTIL NoMoreSwapa = TRUE TASK 11,07 Rewrite the algorithm in Worked Example 1.12 to sort the array elements into descending order Cito cutaine) Working with two-dimensional arrays and nested loops A LD array is like a linear ist. The nth element within the array MyList is referred to as MyListinl two-dimensional (20) array is like a table or matrix. The element in row x and column y of mhistable is referred to as Thistabletx, yl For example to store the value Sin the element in the fourth row and second column, we write: Thistablelé, 2] « 5 epee ee aE acon err ‘When we want to access each element of a 1D array, we use @ loop to access each element in turn, When working with a 2D array, we need a loop to access each row. Within each row ‘we need to access each column. This means we use. loop within a loop (nested loops) In structured English our algorithm is For each row For each column Assign the initial value to the element at the current position We need the identifiers shown in Table 11.15. [Identifier ‘ThisTable(1..4, 1..6) | Table data structure (2D array) to store values MaxRows The number of rows in the table (4in this example) Maxcolumis The number of columns in the table (6 in this example) Row Counter for the row index Coloma Counter for the column index Table 11.15 Identifier table for working with a table Using pseudocode, the algorithm to set each element of array Thistable to 2er0 is FOR Row = 1 70 MaxRows FOR Column « 1 TO MaxColumne ‘ThisTable[Row, Column] « 0 ENDFOR ENDFOR When we wantto output the contents ofa 2D array, we again need nested loops. We want to outputall the values in one row of the array on the same line. At the end of the row, we want to output a new line. FOR Row + 1 70 MaxRows FOR Column « 1 TO MaxColumns. OUTPUT ThisTable(Row, Colum) // stay on sane Line ENDFOR OUTPUT Newline J] wove to next Line for next row ENDFOR Summary ‘© Analgorithm isa sequence of steps that can be carried out to solve a problem. (© Algorithms are expressed using the four basic constructs of assignment, sequence, selection and repetition. © Algorithms can be documented using structured English, pseudocode ora program flowchart. © Logic statements use the relational operators =, <, >, <>, <= and>=and the logic operators AND, ‘Rand NOT. Selection constructs and conditional loops use conditions to determine the steps tobe followed. Chapter 11: Algorithm Design and Problem Solving Exam-style Questions Each digltin the sequence is given a weight depending on its position in the sequence. The leftmost cigit haNWEIENEOEIOD The next digit to the right has a weight of 9, the next one 8 and so on, Values are calculated by multiplying each digit by its weight. These values are added together and the sum is divided by 11. The remainder from this division is subtracted from 11 and isle the che QI ort won 3 hes the remainder fom the cones Complete the flowchart using the statements in the table, Start Statement| Statement number Remainder 1 The Mac Iretetealednnga check dg fora sqience feel 0? pea No Ye] ve ea» —- 8) een Ca aC CUE Cet cia roblem given In structured English. vaflowchart forthe fllowing REPEAT ming UNTIL the aunber iEaTEES- Check whether number ie ir if the number ie positive if the number is negative je from the given flowchart. (SNEED op. 3 Write pseudo« start Come) eed a, (81 Chapter 11: Algorithm Design and Problem Solving 4 Alan uses two 1D arrays, UserList and Passworat.Let. For twenty users, he stores each user Din Useztiat and the corresponding password in PasswardList. For example, the person with user ID Prea22 has password rztase UserList PasswordList (21| Mateos i palma (21|_Freaia 21 204s (3)| _annas fe) jeaa322 [20}| Xeniosa [20] weletmps Alan wants to write an algorithm to check whether a user ID and password, entered by a user, are correct. He designs the algorithm to search UsexLiat for the user ID Ifthe user ID is found, the password stored in PasswordList is to be compared to the entered password. If the passwords match, the login is successful. n all other cases, login is unsuccessful. ‘a Complete the identifier table. 4 Identifier Explanation cee Darayoaorevee De (Sa ss ss passvcc E [MaxIndex Number of elements in each array MyUserID User ID entered to log [UserTdFound | PALSE if user ID not found in. Ea LogindK FALSE if TRUE if ‘Index Pointer to current array element. ee ea Ee ce Rec ete b Complete the pseudocode for Alan's algorithm: Maxtndex = 20 INPUT MyUserrD INPUT MyPassword UsertdFound « FALSE Index « 0 REPEAT LoginOk + TRUE = °° CIES ° OUTPUT "User ID and/or password incorrect" ENDIF ho}

You might also like