Uploaded by malanasimon22

Week 11 Reading

advertisement
Week 11: Array Applications
Table of Contents
Learning Outcomes: ....................................................................................................................... 2
11.1 Introduction ........................................................................................................................... 3
11.2 Element Separators................................................................................................................ 3
11.3 Implementing Linear Search on Arrays .................................................................................. 3
11.4 Removing and Inserting Values in an Existing Array.............................................................. 5
11.4.1 Removing items in an unordered list .............................................................................. 5
11.4.2 Removing Item in an ordered List ................................................................................... 5
11.4.3 Inserting an Element in an Unordered Array .................................................................. 6
11.4.4 Inserting an Element in an Ordered Array ...................................................................... 7
11.5 Swapping Elements ................................................................................................................ 7
11.6 Two Dimensional Arrays ........................................................................................................ 9
11.6.1 Defining Two-Dimensional Arrays ................................................................................... 9
11.6.2 Initializing 2-D Arrays .................................................................................................... 10
11.7 Accessing Element in 2-D arrays .......................................................................................... 11
11.8 Using loops to access 2-D Arrays ......................................................................................... 12
11.9 Calculations on 2-D Arrays – Computing Row and Column Totals ...................................... 13
11.9.1 Computing Row Totals .................................................................................................. 13
11.9.2 Computing Column Totals ............................................................................................. 13
11.10 Passing 2-D Array Parameters to Functions ...................................................................... 13
11.10.1 Common Error in Passing Parameter .......................................................................... 15
CS111: Introduction to Computing Science
1|P a g e
Learning Outcomes:
At the end of this topic, the student is able:








To Understand the common search algorithms based on arrays
To comprehend with the common array algorithms
To compare between linear and binary search
To interpret the swapping algorithm
To Comprehend with the syntax of two dimensional array
To understand how to initialise two dimensional arrays
To implement row and column total calculations in two dimensional arrays
To Understand how to pass 2-D Array as parameter to a function
CS111: Introduction to Computing Science
2|P a g e
11.1 Introduction
In this topic, we will look at some of the applications of arrays in areas such as linear and
binary search, how to swap the elements, sorting arrays and multi-dimensional arrays.
11.2 Element Separators
Figure 11.1: Seperators in Arrays source: C++ for Everyone by Cay Horstmann
11.3 Implementing Linear Search on Arrays
In computer science, linear search or sequential search is a method for finding a particular
value in a list that checks each element in sequence until the desired element is found or the
list is exhausted. The list need not be ordered.
Figure 11.2: How Linear Search Works
CS111: Introduction to Computing Science
3|P a g e
Linear search is the simplest search algorithm; it is a special case of brute-force search. Its
worst-case cost is proportional to the number of elements in the list. Its expected cost is also
proportional to the number of elements if all elements are searched equally.
Figure 11.3: Linear Search Implementation
CS111: Introduction to Computing Science
4|P a g e
The linear search algorithm is very simple. The motive is very simple. To search for all the
values in sequence until the matching value is found. The list may not be sorted. The starting
position is set to 0 and the bool variable is_found set to false. As the comparison is done
element by element, as soon as the match is found, the value of is_found is set to true, which
also terminates the while loop condition. One issue with this algorithm is that it stops as soon
as it finds the matching value rather than competing the search of full list and keeping track of
the total number of correct match.
11.4 Removing and Inserting Values in an Existing Array
11.4.1 Removing items in an unordered list
Suppose you want to remove the element at index i. If the elements in the vector are not in
any particular order, that task is easy to accomplish. Simply overwrite the element to be
removed with the last element of the vector, then shrink the size of the vector by removing
the value that was copied.
Figure 11.4: Removing items in an unordered list (Source: C++ for Everyone by Cay Horstmann)
11.4.2 Removing Item in an ordered List
The situation is more complex if the order of the elements matters. Then you must move all
elements following the element to be removed “down” (to a lower index), and then shrink the
size of the vector by removing the last element.
CS111: Introduction to Computing Science
5|P a g e
Figure 11.5: Removing items in an ordered list (Source: C++ for Everyone by Cay Horstmann)
for (int i = pos + 1; i < current_size; i++)
{
values[i - 1] = values[i];
}
current_size--;
11.4.3 Inserting an Element in an Unordered Array
This situation is a simple one as the values are not in an order. This means that the new
element can be inserted right at the end of the array. Common strategy is to check if the
cuurent size of the array is less than the capacity of the array, and if yes then increment the
current size by 1, and then insert the new element in [current_size -1] index.
Figure 11.6: Inserting Item in an Unordered List Source: C++ for Everyone by Cay Horstmann
CS111: Introduction to Computing Science
6|P a g e
11.4.4 Inserting an Element in an Ordered Array
First, you must make the array one larger by incrementing current_size. Next, move all
elements above the insertion location to a higher index. Finally, insert the new element in the
place you made for it.
Figure 11.7: Inserting item in an ordered list
(Source: C++ for Everyone by Cay Horstmann)
11.5 Swapping Elements
Swapping elements refers to placing two elements in each other’s place. This might look as
simple as this:
values[i] = values[j];
values[j] = values[i];
If you look closely at the two lines then you will realize that when the first line is executed, the
original element of values[i] is being replaced by new value and is lost completely. The second
line is actually copying the same value as the first one.
CS111: Introduction to Computing Science
7|P a g e
Let’s look at the following example:
Imagine if you are given the task of swapping the glasses of this glass of milk and glass of
water. The two lines above basically means pouring the milk into the water and then the water
back to milk.
Figure11. 8: Glass of Milk and Water representing two elements of array to be swapped
By now you must have realized that to swap these two glasses, we need a third glass. Lets call
this glass temporary glass, or temp in short.
Figure 11.9: Empty Glass Representing the temp variable
The method is to:
1. Pour Milk into Temp
2. Pour Water in Milk Glass
3. Pour Milk from the Temp Glass to Water Glass.
That’s it. We have successfully performed the swapping. The same applies to element
swapping in arrays.
CS111: Introduction to Computing Science
8|P a g e
temp = values[i];
values[i] = values[j];
values[j] = temp;
11.6 Two Dimensional Arrays
It often happens that you want to store collections of values that have a two-dimensional
layout. Such data sets commonly occur in financial and scientific applications.
Figure 11.10: Example of Scientific Data which demands the use of 2-D arrays
In the above situation, we have two dimensional data which forms the points for the graph.
We can always put these two data in two different single dimension array but then they will
have no link to each other. To manipulate them we have to assume that the data entry was
done with aligned index. With 2-D arrays, we solve this problem.
11.6.1 Defining Two-Dimensional Arrays
Consider the following data from the Commonwealth Games 2014:
Figure 11.11: Commonwealth Games 2014 Medal Tally
CS111: Introduction to Computing Science
9|P a g e
C++ uses an array with two subscripts to store a two dimensional array.
const int COUNTRIES = 7;
const int MEDALS = 3;
int counts[COUNTRIES][MEDALS];
The array counts has two subscripts: 1) [COUNTRIES]
2) [MEDALS]
It must be noted that just like one-dimensional arrays, the size of two-dimensional arrays in
not changeable once its defined.
11.6.2 Initializing 2-D Arrays
Figure 11.12: Initializing the counts array
Figure 13: Syntax of Two_Dimensional Array Source: C++ for Everyone by Cay Horstmann
CS111: Introduction to Computing Science
10 | P a g e
11.7 Accessing Element in 2-D arrays
Accessing elements in 2-D arrays is more of like accessing data from a table with columns and
rows. From the syntax we now know that 2-D arrays are declared with the number of rows as
first subscript and number of columns as second subscript. As with 1-D arrays, the index of
both row and column starts with 0.
Figure 11.14: 2-D array described visually in tabular form with rows and columns
Here is a list of random request from the medal tally and how will we access it:
Table 1: Various Requests of Data
Request
Access
No. of Gold Medals won by Canada
No. of Silver Medals won by New
Zealand
No. Of Bronze Medals won by South
Africa
counts [2][0]
counts [5][1]
counts [6][2]
Table 1 shows how the access to individual data in the 2-D array works. Canada’s Gold Medal
count is in 3rd row and 1st column and the access is counts [2][0]. One noticeable fact is that
access value of both row and column is always one less than the actual row and column it is.
This is so because both the column and row numbering starts with zero.
CS111: Introduction to Computing Science
11 | P a g e
11.8 Using loops to access 2-D Arrays
You may still recall from week 10 on how we accessed and filled 1D arrays using loops. Of
course loops made it easier and faster to access arrays.
Figure 15: Recall from week 10 Notes: Accessing 1D Arrays
The same can be applied to 2D Arrays. Only issue with 2-D arrays is that they are 2-D. What I
actually mean is that we will need two index value to access array element; one for the rows
and other for columns. This is solved by the nested FOR loop. Nested loop means a loop within
a loop.
for (int i = 0; i < COUNTRIES; i++)
{
// Process the ith row
for (int j = 0; j < MEDALS; j++)
{
// Process the jth column in the ith row
cout << setw(8) << counts[i][j];
}
// Start a new line at the end of the row
cout << endl;
}
In the code above the outer loop uses i and the inner loop uses j. i is used to represent the
rows which are the seven countries. j is used to represent columns which are the three types
of medals. This is how the code will print the medals. Table 2: Table showing the step-by-step
effect of nested loop.
i=1
……………
……………
i=6
j =0
j=1
j=2
counts[0][0]
counts[0][1]
counts[0][2]
counts[1][0]
counts[1][1]
counts[1][2]
Prints England's Gold Medal: 58
Prints England's Silver Medal: 59
Prints England's Bronze Medal: 57
Prints Australia's Gold Medal: 49
Prints Australia's Silver Medal: 42
Prints Australia's Bronze Medal: 46
……………
j =0
j=1
j=2
j =0
j=1
j=2
……………
i=0
counts[6][0] Prints SA's Gold Medal: 13
counts[6][1] Prints SA's Silver Medal: 10
counts[6][2] Prints SA's Bronze Medal: 17
CS111: Introduction to Computing Science
First Row
Second Row
Last Row
12 | P a g e
In total the nested loop will print out [No. of Row x No. of Columns] (7 X3) values i.e. 21 values.
11.9 Calculations on 2-D Arrays – Computing Row and Column Totals
11.9.1 Computing Row Totals
Let’s calculate how many medals were won by each country in total. For this we need to add
the rows of each country.
for (int i = 0; i < COUNTRIES; i++) {
int total = 0;
for(int j = 0; j < MEDALS;j++){
total = total + counts[i][j];
}
cout << "Total Medals won by country no. "
<<i+1<<" is " << total << endl;
}
In this code we can see that when i=0, using the inside FOR loop total = counts[0][0] +
counts[0][1] + counts[0][2] is done and the total for first country which is England is displayed.
Then i value changes to 1 and the same process is repeated until all country medal totals are
calculated and displayed.
11.9.2 Computing Column Totals
Let’s calculate how many Gold Medals, Silver Medals and Bronze Medals were won by these 7
countries. Basically we will total the three medal columns.
for (int j = 0; j < MEDALS; j++) {
int total = 0;
for(int i = 0; i < COUNTRIES;i++){
total = total + counts[i][j];
}
cout << "Total of column no. "
<<j+1<<" is " << total << endl;
}
In this code we can see that when j=0, using the inside FOR loop total = counts[0][0] +
counts[1][0] + counts[2][0] + counts[3][0] + counts[4][0] + counts[5][0] + counts[6][0] is done
and the total for Gold Medal is displayed. Then j value changes to 1 and the same process is
repeated for silver medal totals and bronze medal totals.
11.10 Passing 2-D Array Parameters to Functions
When passing a two-dimensional array to a function, you must specify the number of columns
as a constant when you write the parameter type.
CS111: Introduction to Computing Science
13 | P a g e
table[][COLUMNS]
This function computes the total of a given row.
const int COLUMNS = 3;
int row_total(int table[][COLUMNS], int row)
{
int total = 0;
for (int j = 0; j < COLUMNS; j++)
{
total = total + table[row][j];
}
return total;
}
This function works for only arrays of 3 columns. If you need to process an array with a
different number of columns, like 4, you would have to write a different function that has 4 as
the parameter. What’s the reason behind this? Although the array appears to be twodimensional, the elements are still stored as a linear sequence.
Figure 11.16: How 2D array is actually represented; in a sequence just like single dimension arrays
counts is stored as a sequence of rows, each 3 long. So where is counts[3][1]? The offset from
the start of the array is 3 x number of columns + 1. Let’s see how we came up with this
calculation. Remember there is a mention that even the 2-D array is treated as single
dimension array. Here goes the explanation. This will also solve the mystery on why the
number of columns needs to be passed as a parameter.
Let’s use this example:
cout<< counts [3] [1];
How will the program know which value is being requested here? Remember that we have
passed the information to the function that this array has 3 columns. Now when you are
requesting for the counts [3] [1], it does the following calculation:
Let’s use this general form of array: Array_Name [Row_Value] [Column_Value] then the
calculation is such:
CS111: Introduction to Computing Science
14 | P a g e
Index Accessed
=
=
=
Row_Value * No. of Columns + Column_Value
3*3+1
10
Therefore the index of one dimension array will be 10, which is the eleventh element in the
array taking 0 as the first element.
Let’s use another similar example to confirm this.
counts [4] [2] ;
Index Accessed
=
=
=
Row_Value * No. of Columns + Column_Value
4*3+2
14
Figure 11.17: Shows how individual cells are actually accessed
11.10.1 Common Error in Passing Parameter
Common error in passing parameter of 2-D array to function is leaving the second bracket
empty i.e. no setting the column value.
Figure 11.18: Common Error in passing 2-D array as parameter
By the way, accidently setting the row value is not an error and will be ignored by the compiler
anyway.
CS111: Introduction to Computing Science
15 | P a g e
Figure 11.19: Accidentally setting the Row Value
CS111: Introduction to Computing Science
16 | P a g e
Download