is it in there?

Sometimes you want to know if something is in a list. If the list isn’t sorted, the only way you can know for sure is to look at every item in the list and see if it is what you’re looking for. That is called a sequential search and it’s pretty easy to do. Since we’re using Snap, I’ll draw you a picture.

This script reports whether the item was found in the search or not, but it could be modified to do other things. Suppose for example, you have a list of students and you’re looking for all students named Bob. You don’t want it to simply stop with the first student. So you’d need to modify the search to change the “found” half of the or on the repeat until … and instead have found be a variable that you set to an empty list before the loop and then add the index positions as list items to it when you find a Bob in the class. If there is one. If there are no students named Bob, you would have an empty list, same as what you started with. If there were two students named Bob, you would have a list with two index positions in it, telling you where the name Bob appears in the list.

Of course there are other ways. This is programming and, generally speaking, you can find several valid solutions to any problem.

If the list is sorted, there are shortcuts. You can split the list and look in the part of the list where you know something is. You do this when you look through any alphabetized anything. You know not to look for something that starts with a  in the r section.

Leave a Reply

Your email address will not be published. Required fields are marked *