ELECTRICAL AND COMPUTER ENGINEERING 06-88-211: COMPUTER AIDED ANALYSIS LABORATORY EXPERIMENT #2: INTRODUCTION TO ARRAYS SID: OBJECTIVE: SECTIONS: Total Mark (out of 20): To become familiar with array manipulation, searching, and sorting. 1. Filling and Manipulating Arrays (5 marks) 2. Searching Arrays (3 marks) 3. Sorting Arrays (9 marks) 4. Searching Sorted Arrays (3 marks) INSTRUCTIONS: Carry out the coding experiment and submit your results on this paper at next week s lab. 1. FILLING AND MANIPULATING ARRAYS In Lab 1 we started to use control structures such as if, for, etc. to begin to analyze data. We will continue by first creating some new data to manipulate. Generally we could use a series of random numbers but since there are a variety of C++ compilers in use by the students it will be difficult to get the same results as these compilers generate random numbers differently. We will simplify our approach by generating a series of 20 (adjustable by modifying the #define entries line) predictable numbers which will appear random by are really not. Please begin by copying this code into a new project. If you are using Visual C++ make sure you add it after the #include stdafx.h. #include <iostream> #include <iomanip> using namespace std; #define entries 20 int main() int i,j,v; int list1[entries], list2[entries]; for(i = 0, j = 0; i < entries; i++, j += 1299827) v = (j % 1024); /* set array values here */ return 0; Your task is to add code which will set the ith element of list1 and list2 to v, for i s from 0 to entries-1. Write only that code below: 06-88-211 Laboratory #2 1/5
Just above the return 0 add code which will print out contents of list1 and list2 preceded by its element index (one element index per line). Write only that code below: Now we will begin to do a little data manipulation using the skills we have developed so far. Add code before where you print the contents of the lists that will add the ith and ith+1 entry of list1 together and store it in the ith entry of list2 and subtract the ith+1 entry from the ith entry of list1 and store it in the ith+1 entry of list2. You should start at the first entry, 0 and skip every two entries when performing this task. Write only that code below: Verify that your output is correct by doing some mental math. It is easy to use software to manipulate numbers mathematically. It is just a matter of knowing what is necessary to do and then apply it in the proper order when writing software. 2. SEARCHING ARRAYS Remove the above code fragment from your base code. We will now write some code which will search for the largest element in list2 (we will leave list1 in its original state so we can use it to compare our results later). There are a number of approaches which can be used for searching, but given that our data is not sorted in any specific order, this leaves us with far fewer options. We will use an approach where we keep track of the largest element by remembering its element number or index in the array not necessarily its value (we can just reference the array to find that out). We will use a new integer for this, it is essentially a flag; call it whatever you like but make sure it is initially set to 0. This will imply that the largest element is the first one in the list, a reasonable assumption at this point. To guarantee that this index refers to the largest value in list2 then we have to compare it with all the other items in list2. We need a loop for this; it should start at the second element (since we already said the first is currently the largest) and go all the way to the last. Every time we find a value that is larger than the current one, we will replace it with the new index of the larger value. When your loop is done we will know which entry in list2 has the largest value. Write only this code below: 06-88-211 Laboratory #2 2/5
Given that we have 20 items in our list, it took 19 comparisons to find the largest one. It would take a similar number of comparisons, on average, if we were to look for a particular value or range of values. This is because the list of items is not sorted. We know that when we need to access information often the best way to do this is when it is sorted. For example, if you need to look-up a word in a dictionary or thesaurus we simply look at the first few letters of the word to determine its location. If the words in either of these books were unsorted it could take a very long time to find them. So we will modify our code to sort the items in list2 from highest to lowest. Just like searching for information there are a number of methods to sort information. We will examine a simple approach which may take more time than other methods but it is easier to understand and it is based on the method we used to search for the largest value. 3. SORTING ARRAYS At this point we know the index of the largest value so we now need to place the largest value into the first index. To do this we will swap the two elements, the current first value and the largest value. It is possible that the first value is already the largest value so we could place a condition on our swapping code not to actually swap them if it is already in the proper place. To do a swap we move information from one location which we will call position1 into another which we call position2, and the original information in position2 must be moved to position1. Computers don t have short term memory like us so we have to properly instruct them on how to swap the values. To do this properly we must save the information in position2 first before we overwrite it from that of position1. We will therefore need a temporary variable to hold this, so copy the information in position2 first to the temporary location, then copy the information in position1 to position2, and then copy the information in the temporary variable to position1. Write the code below that does this: At this point the first element in list2 should be the highest but all the other elements are unsorted. To completely sort of all elements in the list we do the same operation as we did before but we start at the second item. Again we use our flag to indicate that this is the largest value and search the remaining items to see if any of those are larger. If this is the case, we update our flag and move on. When this loop is done, we swap the largest element with the second one in the list and now our list has the two largest items at the top of the list. We continue to do this until we are on the second last item. Our loop at this point will only compare it to the last, and will swap them if necessary. This approach is called a selection sort since we are selecting the largest item in our list and moving it to the beginning of our list. To code this we need two nested loops. The outer loop will go from the first to the second last elements (0 to entries-2 inclusively). Inside this loop you will place your code for searching for and swapping the largest value. Be careful to change the references from the first element, 0, to the value of the outer loop counter. Your inner loop should go from the current outer loop element plus 1 to the last (entries-1) inclusively. Write your code below that does this: 06-88-211 Laboratory #2 3/5
Your output should show the index and values of list1 and list2 side by side such that list1 is unsorted and list2 is sorted. If we wanted to make is so that list2 was sorted smallest to largest, what single line change would be required in the above code to do this? Write only that modified line below: Now that we have sorted data, we can search it easier. Apply the above change so that the code will generate lists sorted smallest to largest for the next lab section. Before moving on we will examine the number of repetitions that occurred in this sorting loop. Add a new variable, n, and initialize it to 0 before sorting the array, then increment n each time we perform one iteration of the inner loop. Indicate the value of n below given the 20 values in our array. Now increase the elements in our array to something larger (ie. change value on #define line). How has n changed? Can you predict the value of n based on the number of elements in the array? 4. SEARCHING SORTED ARRAYS We have seen previously that searching an unsorted array in a linear order for a particular item takes approximately n iterations. Once the array is sorted however the number of iterations on average drops to n/2 06-88-211 Laboratory #2 4/5
since we can stop searching once we have exceeded those values in the list. Using whatever value for the number of elements, add the following to your code just before the return 0; line and run it. for (j = 0; j < entries; j++, n++) if (i == list1[j]) break; cout << "Iterations for linear search in unsorted array: " << n << endl; for (j = 0; j < entries; j++, n++) if (i <= list2[j]) break; cout << "Iterations for linear search in sorted array: " << n << endl; The first part of the code searches the unsorted array for all values between 0 and 1023 (our range of data) and then reports the total number of iterations. The second part of the code searches the sorted array for the same values and reports the number of iterations. Enter your results below along with the number of iterations for both cases. Based on the number of elements in the array, do these results corroborate with the earlier statements? When dealing with sorted arrays it is clear that performing a linear search is not the most efficient method to find information. One of the most efficient approaches is called a binary search; this is typically what we do when we search for something, we just aren t aware of it. An excellent example of this is the number guessing game where all you are told is whether your guess is lower or higher than the target. If you are asked to guess a number between 1 and 16, what is the best first choice? 8 of course since it is the mid-point between 1 and 16. If you were told that your guess was lower than the target value, you would then proceed to guess the mid-point between 8 and 16 which is 12. If you were then told lower, you would guess the mid-point between 8 and 12 which is 10. And finally if you were told higher, you would select the mid-point between 10 and 12 which is 11 the correct answer. It only took 4 tries with 16 elements with a binary (2) search. Remember this for later. Add the following code before the return 0 which illustrates the binary search with our sorted array and run it. int u = entries, l = 0; while (l<u) n++; j = l + (u - l) / 2; if (i < list2[j]) u = j; else if (i > list2[j]) l = j+1; else break; cout << "Iterations for binary search in sorted array: " << n << endl; This code searches the array using a binary search for all values between 0 and 1023. Your result should be far less than the linear search on the sorted array. Determine the relationship between the number of iterations and elements in the array for the binary search? 06-88-211 Laboratory #2 5/5