SCRATCH MODULE 2: SORTING INTRODUCTION The purpose of this module is to experiment with repetition, variables, and lists in Scratch. We will be exploring these ideas while implementing two sorting algorithms. Our program will create a list of 10 randomly selected numbers and allow the user to modify the list by adding additional elements, changing existing elements, or deleting elements. When the list is ready, the user will select either ‘Selection sort’ or ‘Bubble sort’. At that point, the original list is copied to a secondary list and the chosen sort is performed. A timer is used to indicate how long the sort took. After this, the user may choose to perform the other sorting algorithm or modify the original list and repeat the process once again. It is assumed that students have successfully completed the ‘Scratch Tutorial’ and ‘Scratch – Module 1’ prior to beginning this module. Students must have sufficient knowledge of the Scratch working environment to create, modify, and execute scripts as well locate blocks within categories and modify them according to directions and examples provided. It is recommended that students follow these instructions closely to achieve the desired end product. Personalization of the project is encouraged but better done once these instructions have been completed to ensure all outcomes have been accomplished. NEW CONCEPTS COVERED Variables: Create / Hide / Show / Set / Change / Scope Using random numbers Counting Page 1 Lists: Create / Hide / Show / Scope Add items to a list / Insert into list Replace items in a list / Delete items from a list Retrieve a single item from a list Determine the number of items in a list Use a counter variable to access individual items in a list Repetition: Repeat / Repeat until Comparison operators: Timer: </>/= Reset timer Use a timer variable to keep track of elapsed time STARTING SCRATCH Start Scratch. Create a new Scratch project by selecting ‘File’ > ‘New’. Before we do anything, let’s save the file by selecting ‘File’ > ‘Save as’. Save your file as ‘Module 2 – XY’ where X is the initial of your first name and Y is the initial of your last name. Remember to save to your network drive! If this doesn’t work, please ask your Lab Instructor for assistance. PART 1: SETTING THE STAGE The best way to learn Scratch is through experimentation. As it is an interactive environment, feel free to stop and experiment as you work through this module. CREATING THE SPRITES Let’s get started … Sprite1 (the cat): At the moment, our current sprite is Sprite1 (the cat). For the moment, we don’t need him. Double-click the category to hide him. block under the Sprite2 (title): We need to create a title for our game. Select the first option to ‘Paint new sprite’. Select in the Paint Editor screen and the Text tool type in a title such as ‘Sorting Algorithms’. If you can’t see your text, grab the little black box to the left of the text and drag the text to where you can see it. You can change the text color (perhaps to orange) and size (to something like 24) if you want. When ready, click ‘OK’. Position the title properly in the top center of the stage. Use Figure 1a to help you. Adjust the coordinates if necessary. Figure 1a Page 2 Sprite3 (instructions): We need to give the user instructions for operating our game. Once again, select the first option to ‘Paint new sprite’. Using the Text tool, type in the instructions ‘Finalize the original list. Click a sort button to begin.’ Grab the little black box to the left of the text and drag the text to where you can see it. If you can’t quite see all of it, click on the magnifying glass with the minus sign in it to zoom out. Once you can read all of it, use the ‘Enter’ key between the two sentences to separate them so they appear on two different lines. You may also want to use the spacebar to center the first one above the second. Change the size to something smaller (like 12) before continuing. When done, click ‘OK’. Build the script in Figure 1a but use x = 10, y = -140. Adjust the coordinates as needed to center the instructions just above the bottom of the screen. Sprite4 (button): We need to give the user a button for the first sort. Once again, select the first option to ‘Paint new sprite’. Using the Text tool, type ‘Selection Sort’. Change the size to something smaller (like 12). Then click on the Rectangle and draw a rectangle over ‘Selection Sort’. Click on the Fill tool tool and use the eyedropper to select a color from the palette (like light blue) and then click on the rectangle to change its color. You should now see the words clearly. If the words are not centered, you can reselect the Text tool and reposition the words within the rectangle accordingly. When done, click ‘OK’. To position the button to the left and slightly underneath the title, use the script from Figure 1a with x = -157, y = 131. Sprite5 (button): Now we need a button for the second sort. Since this button is almost identical to the previous one, right click on the previous button in the Sprite List and ‘Duplicate’ it. Click on the ‘Costumes’ tab for Sprite5 and ‘Edit’ costume1 so it says ‘Bubble Sort’ instead. When finished, click ‘OK’. Finish up by going to the ‘Scripts’ tab and editing the position to x = 175, y = 131. Click the green flag to position the sprites on stage. Page 3 PART 2: PREPARING THE DATA Before we can start sorting, obviously we need something to sort. The main source of data for our program will be a list we’ll call ‘Original’. The program should fill it with 10 random numbers to start with but allow the user to modify those numbers, add extra numbers, and delete numbers already present. Accessing information in a list can be a bit tricky. Since a list can store multiple items, retrieving an item means specifying where the item is in the list. Consider our ‘Original’ list with a maximum of 10 items. The first item would be in position 1, the second in position 2, and so on with the last item in position 10. If I wanted to retrieve the fourth item in the list, I would need to indicate that I wanted the item in position 4. If I wanted to retrieve all items in a list, I would need to first retrieve the item in position 1, then the one from position 2, and so on until all items have been retrieved. When we wish to access all items in a list one by one, we will typically use a loop with a counter variable. You will see this often throughout the remainder of this module. Lists, just like variables, are not sprites in Scratch. Instead, they belong to all sprites at once. We will use different Sprites to manage the lists. Time to set up our data … CREATING THE LISTS Original: Select the Stage from the Sprite List to make the Stage active. We are going to have the Stage set up the ‘Original’ list before the sorts commence. From the Block . Descriptions, select Anything pertaining to a variable or list will be found in this category. and fill in the Choose information as shown in Figure 2a. Click on ‘OK’ when ready. Figure 2a Now you should see the ‘Original’ list in the upper right corner of the stage. It is empty and has shows ‘length: 0’ because there are no elements in the list. Grab the ‘Original’ list and move it so it appears centered directly below the title. Now it’s ready to use. List A: We will use a separate list when we perform ‘Selection Sort’ called ‘List A’. and name it ‘List A’ when prompted. Reposition the list so it Choose appears centered underneath the ‘Selection Sort’ button. List B: You can probably guess what happens next. ‘List B’ is the list we’ll use when and name it ‘List B’. we perform ‘Bubble Sort’. Once again, choose Reposition the list so it appears centered underneath the ‘Bubble Sort’ button. Page 4 CREATING A VARIABLE Size: To keep track of how many items are in the current list, we’ll make a variable called ‘Size’. From the Block Descriptions, select . Choose and fill in the information as shown in Figure 2b. Click on ‘OK’ when ready. Now you should see Figure 2b in the upper left corner of the stage. It appears has the check mark selected. By clicking the check mark, you because can unselect it and the variable will disappear from the stage. Do this now. We don’t want the user to see Size. FILLING THE LIST WITH RANDOM NUMBERS Now it’s time to fill the ‘Original’ list with 10 random numbers. The random numbers can be anything between 1 and 100. We will do this by picking a random number between 1 and 100 and then inserting it somewhere in the ‘Original’ list and then repeating this process 10 times. Use blocks from the categories for the next section. , Setting a value: Re-select the Stage from the Sprite List if it is not currently active. We’ll start by setting the desired amount of elements allowed in the list to 10. Create the script shown in Figure 2c. , and Figure 2c Deleting / Inserting elements: Now we will delete all elements in the list (a good habit to ensure the list is Figure 2d empty) and insert a random number between 1 and 100. Expand the script from Figure 2c with that of Figure 2d. Be certain that you are changing the ‘Original’ list. Each time you click the green flag, you will see your ‘Original’ list change. One number will be shown and the list ‘length’ will show ‘1’. To put all 10 elements in the list, we need to perform the insert process 10 times. What we need is a loop… Page 5 USING A COUNTING LOOP Repeating a process a certain amount of times is easily accomplished using the and the With the blocks found in the category. block, you can indicate the amount of times to repeat with a typed in number or with a counter variable instead. The block will repeat until a certain condition is met. A counter variable could be used here so that the repetition will continue until the counter reaches a specific value. There are other uses as well. In this module we will practice using loops. from Figure 2d Repeat: Surround the with a block to make it repeat 10 times. Then, replace the ‘10’ with the variable since that is what it represents. When you are finished, you should have created the script in Figure 2e. We now have data to sort! Figure 2e MANUALLY EDITING A LIST When you click the green flag now, you will see some elements and the ‘length’ should show 10. You may need to use the scroll bar to see the top of the list. To see all of the elements, click on the bottom right corner of the list and resize the list. Before we sort this data, you will have the opportunity to edit the list. By clicking the on the bottom left corner of the list, an extra space will appear in the list. You can click in this space and type in a new number. As soon as you click in the space, you will see to the right of the space. When you click the , you will delete the element in this position. In this way, you can manually add values, delete values, and edit values in this list. Page 6 PART 3: SETTING UP FOR SELECTION SORT When the user is ready, s/he will choose one of the two sorts by pushing the appropriate button. If Selection sort is chosen, the ‘Original’ list will be copied to ‘List A’ and the sort will commence. If Bubble sort is chosen, the ‘Original’ list will instead be , copied to ‘List B’ before sorting begins. Continue using blocks from the , and categories for the next section. SENDING MESSAGES Broadcast: Select Sprite4 from the sprite list. Start a new script with Figure 3a and snap two blocks underneath. Update the first broadcast by clicking the down arrow and creating a new message called ‘Create List A’. Update the second one with the new message ‘Perform Selection Sort’. You should now see the script from Figure 3a. RECEIVING MESSAGES When I receive: Start a new script with and change the message to ‘Create List A’ as shown in Figure 3b. Figure 3b COUNTER VARIABLE To copy one list to another requires a counting variable. i: Select , choose , name it ‘i', make it ‘For all sprites’, and hide it from the stage when finished. copy values between lists. will function as a counter while we ACCESSING VARIABLE AND LIST ELEMENT VALUES The script to copy the lists will use to count through all positions in the list. will represent the list size. Since the user had the option to add or delete elements, we no longer can be sure of the size. We will use the block also from the category to find out how many elements are currently in the list. We will use the replace the to access an item in a specific position of the list. We can with a counter variable like to further control which item is accessed. Page 7 COPYING A LIST Insert: Expand the script started in Figure 3b to that of Figure 3c. When you click the green flag and then the ‘Selection Sort’ button, the ‘Original’ list should be copied into ‘List A’. As before, if you cannot see all of the list, click on the bottom right corner of the list and resize it accordingly. One list down … Delete everything from List A Update Size accordingly Start i at position 1 Repeat until all items have been copied Copy the element at position i in the Original list into position i in List A Increase i by 1 (move to next position) Figure 3c PART 4: SETTING UP FOR BUBBLE SORT … and one to go. This phase is identical for both sorts so COPY the script from Figure 3a by dropping it on top of Sprite5 in the sprite list. Do the same for the script from Figure 3c. Then, click on Sprite5 to make it the active sprite. Modify the two scripts you copied into Sprite5 so that they reflect the Bubble sort and the use of List B. When you are finished, your scripts should be identical to those shown in Figure 4a. Notice that there are two occurrences of ‘List B’ in the second script. Ensure you update both of them! Now click on the green flag and then click on the ‘Bubble Sort’ button. If the ‘Original’ isn’t copied into ‘List B’, double check your work. As before, you will want to make ‘List B’ larger on the stage in order to see all of the elements. Now we can start sorting … Figure 4a Page 8 PART 5: PERFORMING SELECTION SORT The Selection sort algorithm we will be implementing is based on the one found in the ‘Lab 3 – Sorting algorithms’ sheet. We will be staying as true to this version as we can. Since you have studied it in both lecture and lab, you should have a good , understanding of how it works. As before, continue using blocks from the , and sprite list and we’ll begin. categories for the next section. Click on Sprite4 from the ALGORITHM DESCRIPTION Selection sort works by repeatedly finding the largest element in the unsorted section and then exchanging it with the last element in the unsorted section. After each pass is completed, one more number is added to the sorted section and the unsorted section is decreased by one. The exception is the final pass where the last two items join the sorted section. Ultimately, it will perform (N – 1) passes where N is the number of elements in the unsorted section initially. Each pass will cause one exchange to be performed. CREATING MORE VARIABLES The remaining three variables should all be ‘For all sprites’ and hidden from the stage once created. Refer to previous sections if you cannot remember how to create variables. N: Create a variable called ‘N’ which will represent the position of the last element in the unsorted section of the list. max_position: Create a variable called ‘max_position’ which will be used to represent the position of the current largest element in the list. temp: Create a variable called ‘temp’ which will be used as a temporary storage location when values are exchanged. The element in the largest position of the list (as indicated by max_position) will be exchanged with the last number in the unsorted section of the list (as indicated by N). Direct exchange doesn’t work; a value is always lost. To exchange the numbers, we need to copy one of them (the item in the last position of the unsorted section) to temp. Then we replace the item in that position with the maximum value. Lastly, we update the maximum with the value from the end of the unsorted section (now stored in temp). SORTING THE NUMBERS Implement the script shown in Figure 5a. When you’re ready, click the green flag and then push the ‘Selection Sort’ button. It should sort the numbers for you. Be very careful – watch the nesting! Remember to double check your work. Halfway there … Page 9 Make N the size of the unsorted section Repeat until all list items have been considered (N – 1 times) Assume max is in position 1 Begin at position 2 Go through each item in the unsorted section Compare each number to the max. If a larger number is found, update max_ position Move to the next position Exchange the item in the largest position with the item at the end of the unsorted section Decrease the unsorted section by 1 Figure 5a PART 6: PERFORMING BUBBLE SORT The Bubble sort algorithm we will be implementing is also based on the one found in the ‘Lab 3 – Sorting algorithms’ sheet. We will be staying as true to this version as we can. Since you have studied it in both lecture and lab, you should have a good , understanding of how it works. As before, continue using blocks from the , and sprite list and we’ll begin. categories for the next section. Click on Sprite5 from the ALGORITHM DESCRIPTION Bubble sort works by repeatedly finding the larger of each pair of items and moving the larger of each pair to the right. At the end of each pass, once all numbers in the unsorted section have been compared in this pairwise fashion, the next largest number will have moved into the sorted section. After each pass is completed, one more number is added to the sorted section and the unsorted section is decreased by one. The exception is the final pass where the last two items join the sorted section. Ultimately, it will perform (N – 1) passes where N is the number of elements in the unsorted section initially. Each pass may cause multiple exchanges to be performed. As with Selection sort, is used to exchange numbers when necessary. Page 10 SORTING THE NUMBERS Implement the script shown in Figure 6a. BE CAREFUL – it’s very easy to make a mistake in this script. Be sure you reference ‘List B’ everywhere not ‘List A’. When you’re ready, click the green flag and then push the ‘Bubble Sort’ button. It should sort the numbers for you. If it doesn’t, double check your work. Almost done … Make N the size of the unsorted section Repeat until all list items have been considered (N – 1 times) Start at the first item and go through each item in the unsorted section Compare each number to the one beside it. If the larger number of the pair is on the left, exchange it with the one on its right. Move to the next position Decrease the unsorted section by 1 Figure 6a PART 7: TIMING IS EVERYTHING We have no way to measure the performance of our algorithms at this point. One way would be to see how long it takes to actually perform the sorts. Let’s add a timer for Selection sort … ONE MORE VARIABLE Time A: Select Sprite4 from the Sprite List. Create a variable called ‘Time A’ which will be ‘For all sprites’. This time, DO NOT hide it from the stage. Instead, drag it underneath of ‘List A’ on the stage. If you want, you can click on it a few times so it only shows the number and not the description. It’s now ready to use … Page 11 USING THE TIMER Timer / Reset Timer: Under the category, you can find a special variable called that simply counts elapsed time. You can use to start it counting at a certain point in time but you cannot stop it. We are going to reset the time just before we begin the sort and then copy the time into our ‘Time A’ variable when we’re finished so we can display the result. Click on Sprite4 once more. Modify the script from Figure 3a into the script shown in Figure 7a. Try the sort once more and you should see the result. Now it’s time to polish up. Figure 3a Figure 7a PART 8: FINISHING UP Clicking the green flag now causes some confusion. We should not have values for ‘List A’, ‘List B’, or ‘Time A’ when we begin. They should be set later on. One last modification … RESETTING THE VALUES Resetting: Click on the stage in the sprite list. Modify the script from Figure 2e into the script shown in Figure 8a. Now all values are all reset appropriately. Great work! Figure 8a Page 12 PART 9: CHALLENGE WORK To get full marks for this assignment, you need to upgrade this sorting example into something more informative. You must implement AT LEAST ONE idea from the list below although you can add other ideas of your own too. When you’re finished, electronically submit this Scratch project for marking through Blackboard. Have fun! IDEAS FOR IMPROVEMENT 1. Timing Bubble sort: Modify Bubble sort just as we modified Selection sort so that it shows how long each Bubble sort takes. Ensure that when the green flag is pushed, the time is reset to zero. 2. Counting Exchanges: Timing is the only measure of performance right now. Modify either (or both) algorithms by adding in a new variable (Exchanges) and set it up so that it counts how many exchanges are performed by either (or both) algorithms. It should also be reset when the green flag is pushed. It could be located on screen below the instructions. 3. Counting Comparisons: As above but with comparisons. Modify either (or both) algorithms by adding in a new variable (Comparisons) and set it up so that it counts how many comparisons are performed by either (or both) algorithms. It should also be reset when the green flag is pushed. It could be located on screen below the instructions. 4. Varying list size: We have assumed that the ‘Original’ list will have 10 elements. Change this assumption. Create a new costume for Sprite1 that will indicate to the user to ‘Set the slider to the number of elements to sort and click anywhere to continue.’ Then create a script for this sprite so it will itself when the green flag is clicked. It should use to show the ‘Size’. The user should be able to enter a value (click on the variable on the stage until it switches to a slider view – the user can slide to any value they want) and click on the screen to continue. When Sprite1 is clicked, it should itself and use the block to hide the ‘Size’. It should then send a message to the Stage so it can proceed with its initialization and display the ‘Original’ list with the amount of values as indicated by the user. The rest of the program should proceed as before. References 1. Scratch v1.4: http://scratch.mit.edu/ Page 13