Page 248 - Learn To Program With Scratch
P. 248

try it out 9-5
                            Combine FindAverage, FindMax, and FindMin into one procedure (called
                            ProcessList) that will display the average, maximum, and minimum values for
                            the score list all at the same time .




              Searching and Sorting Lists

                         Suppose you have a list of contacts that isn’t in any particular order. If you
                         wanted to organize the contacts, you might sort them into alphabetical order
                         based on their names. If you need to know someone’s phone number and
                         you have their last name, you’ll need to search the list to see if it contains
                         that person’s contact information. The goal of this section is to introduce
                         basic programming techniques for searching and sorting lists.

                         Linear Search

            SearchList .sb2  Scratch’s contains block provides an easy way to check whether a list contains
                         a specific item. If, in addition, we’d like to know the position of the item
                         being searched for in a list, then we have to perform the search ourselves.
                             This section will explain one method for searching lists, called a linear
                         search (or sequential search). The method is easy to understand and imple-
                         ment, and it works on any list, whether it is sorted or not. However, because
                         a linear search compares the target value with every element in the list, it
                         can take a long time if your list is large.
                             To illustrate, suppose you’re searching for a specific item in a list
                         named fruit. If the list contains the item you are looking for, you also need
                         to know the exact position of that item. The SearchList procedure shown in
                         Figure 9-19 performs a linear search on the fruit list to give us the answers
                         we seek.



















                         Figure 9-19: The SearchList procedure





           226   Chapter 9
                                           www.it-ebooks.info
   243   244   245   246   247   248   249   250   251   252   253