sa07slide(singledimensionalarray)
TRANSCRIPT
-
8/7/2019 sa07slide(SingleDimensionalArray)
1/47
1
Single-DimensionalArrays
-
8/7/2019 sa07slide(SingleDimensionalArray)
2/47
2
Introducing Arrays
Array is a data structure that represents a collection of thesame types of data.
5.6
4.5
3.3
13.2
4.0
34.33
34.0
45.45
99.993
111.23
double myList [10];
myList[0]
myList[1]
myList[2]
myList[3]
myList[4]
myList[5]
myList[6]
myList[7]
myList[8]
myList[9]
Element value
Array element at
index 5
-
8/7/2019 sa07slide(SingleDimensionalArray)
3/47
3
Declaring Array Variablesdatatype arrayName[arraySize];
Example:
double myList[10];
C++ requires that the array size used to declare an array must be a
constant expression. For example, the following code is illegal:
int size = 4;
double myList[size]; // Wrong
But it would be OK, if size is a constant as follow:
const int size = 4;
double myList[size]; // Correct
-
8/7/2019 sa07slide(SingleDimensionalArray)
4/47
4
Arbitrary Initial Values
When an array is created, its elementsare assigned with arbitrary values.
-
8/7/2019 sa07slide(SingleDimensionalArray)
5/47
5
Indexed VariablesThe array elements are accessed through the index. Arrayindices are 0-based; that is, they start from 0 to arraySize-1.In the past example , myList holds ten double values andthe indices are from 0 to 9.
Each element in the array is represented using thefollowing syntax, known as an indexed variable:
arrayName[index];
For example, myList[9] represents the last element in thearray myList.
-
8/7/2019 sa07slide(SingleDimensionalArray)
6/47
6
UsingIndexed Variables
After an array is created, an indexed variable canbe used in the same way as a regular variable.
For example, the following code adds the value
in myList[0] and myList[1] to myList[2].
myList[2] = myList[0] + myList[1];
-
8/7/2019 sa07slide(SingleDimensionalArray)
7/47
7
No Bound Checking
C++ does not check arrays boundary. So, accessing
array elements using subscripts beyond the
boundary (e.g., myList[-1] and myList[11]) does
not cause syntax errors, but the operating systemmight report a memory access violation.
-
8/7/2019 sa07slide(SingleDimensionalArray)
8/47
8
Array Initializers
Declaring, creating, initializing in one step:
dataType arrayName[arraySize] = {value0, value1,
..., valuek};
double myList[4] = {1.9, 2.9, 3.4, 3.5};
-
8/7/2019 sa07slide(SingleDimensionalArray)
9/47
9
Declaring, creating, initializing
Using the Shorthand Notation
double myList[4] = {1.9, 2.9, 3.4, 3.5};
This shorthand notation is equivalent to thefollowing statements:
double myList[4];
myList[0] = 1.9;myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
-
8/7/2019 sa07slide(SingleDimensionalArray)
10/47
10
Implicit Size
C++ allows you to omit the array size whendeclaring and creating an array using an initilizer.
For example, the following declaration is fine:
double myList[] = {1.9, 2.9, 3.4, 3.5};
C++ automatically figures out how many elementsare in the array.
-
8/7/2019 sa07slide(SingleDimensionalArray)
11/47
11
Partial Initialization
C++ allows you to initialize a part of the array. Forexample, the following statement assigns values
1.9, 2.9 to the first two elements of the array. The
other two elements will be set to zero. Note that ifan array is declared, but not initialized, all its
elements will contain garbage, like all other local
variables.
double myList[4] = {1.9, 2.9};
-
8/7/2019 sa07slide(SingleDimensionalArray)
12/47
12
Initializing Character Arrays
char city[] = {'D', 'a', 'l', 'l', 'a', 's'};
char city[] = "Dallas";
This statement is equivalent to the preceding statement,except that C++ adds the character '\0', called the nullterminator, to indicate the end of the string, as shown inFigure below.
city[0] city[1]
'D' 'a' 'l' 'l' 'a' 's' '\0'
city[2] city[3]city[4]city[5] city[6]
-
8/7/2019 sa07slide(SingleDimensionalArray)
13/47
13
Initializing arrays with random
values
The following loop initializes the array myList withrandom values between 0 and 99:
for (int i = 0; i < ARRAY_SIZE; i++){
myList[i] = rand() % 100;
}
-
8/7/2019 sa07slide(SingleDimensionalArray)
14/47
14
Trace Program with Arrays
int main()
{
int values[5]={0};
for (int i = 1; i < 5; i++){
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
Declare array variable values, create an
array, and assign its reference to values
After the array is created
0
1
4
0
0
0
0
0
animation
-
8/7/2019 sa07slide(SingleDimensionalArray)
15/47
15
Trace Program with Arrays
int main()
{
int values[5]={0};
for (int i = 1; i < 5; i++){
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
i becomes 1
After the array is create
0
1
4
0
0
0
0
0
animation
-
8/7/2019 sa07slide(SingleDimensionalArray)
16/47
16
Trace Program with Arrays
int main()
{
int values[5];
for (int i = 1; i < 5; i++){
values[i] = values[i] + values[i-1];
}
values[0] = values[1] + values[4];
}
i (=1) is less than 5
After the array is create
0
1
4
0
0
0
0
0
animation
-
8/7/2019 sa07slide(SingleDimensionalArray)
17/47
17
Trace Program with Arrays
int main()
{
int values[5]={0};
for (int i = 1; i < 5; i++){
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
After this line is executed, value[1] is 1
After the first iteration
0
1
2
3
4
0
1
0
0
0
animation
-
8/7/2019 sa07slide(SingleDimensionalArray)
18/47
18
Trace Program with Arrays
int main()
{
int values[5]={0};
for (int i = 1; i < 5; i++){
values[i] = i + values[i-1];
}
values[0] = values[1] +values[4];
}
After i++, i becomes 2
animation
After the first iteration
0
1
2
3
4
0
1
0
0
0
-
8/7/2019 sa07slide(SingleDimensionalArray)
19/47
19
Trace Program with Arrays
int main()
{
int values[5]={0};
for (int i = 1; i < 5; i++)
{
values[i] = i + values[i-1];
}
values[0] = values[1] +
values[4];}
i (= 2) is less than 5
animation
After the first iteration
0
1
2
3
4
0
1
0
0
0
-
8/7/2019 sa07slide(SingleDimensionalArray)
20/47
20
Trace Program with Arrays
int main()
{
int values[5]={0};
for (int i = 1; i < 5; i++){
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After this line is executed,
values[2] is 3 (2 + 1)
After the second iteration
0
1
2
3
4
0
1
3
0
0
animation
-
8/7/2019 sa07slide(SingleDimensionalArray)
21/47
21
Trace Program with Arrays
int main()
{
int values[5]={0};
for (int i = 1; i < 5; i++){
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
After this, i becomes 3.
After the second iteration
0
1
2
3
4
0
1
3
0
0
animation
-
8/7/2019 sa07slide(SingleDimensionalArray)
22/47
22
Trace Program with Arrays
int main()
{
int values[5]={0};
for (int i = 1; i < 5; i++){
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
i (=3) is still less than 5.
After the second iteration
0
1
2
3
4
0
1
3
0
0
animation
-
8/7/2019 sa07slide(SingleDimensionalArray)
23/47
23
Trace Program with Arrays
int main()
{
int values[5]={0};
for (int i = 1; i < 5; i++){
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
After this line, values[3] becomes 6 (3 + 3)
After the third iteration
0
1
2
3
4
0
1
3
6
0
animation
-
8/7/2019 sa07slide(SingleDimensionalArray)
24/47
24
Trace Program with Arrays
int main()
{
int values[5]={0};
for (int i = 1; i < 5; i++){
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
After this, i becomes 4
After the third iteration
0
1
2
3
4
0
1
3
6
0
animation
-
8/7/2019 sa07slide(SingleDimensionalArray)
25/47
25
Trace Program with Arrays
int main()
{
int values[5]={0};
for (int i = 1; i < 5; i++){
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
i (=4) is still less than 5
After the third iteration
0
1
2
3
4
0
1
3
6
0
animation
-
8/7/2019 sa07slide(SingleDimensionalArray)
26/47
26
Trace Program with Arrays
int main()
{
int values[5]={0};
for (int i = 1; i < 5; i++){
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
After this, values[4] becomes 10 (4 + 6)
After the fourth iteration
0
1
2
3
4
0
1
3
6
10
animation
-
8/7/2019 sa07slide(SingleDimensionalArray)
27/47
27
Trace Program with Arrays
int main()
{
int values[5]={0};
for (int i = 1; i < 5; i++)
{
values[i] = i + values[i-1];}
values[0] = values[1] + values[4];
}
After i++, i becomes 5
animation
After the fourth iteration
0
1
2
3
4
0
1
3
6
10
-
8/7/2019 sa07slide(SingleDimensionalArray)
28/47
28
Trace Program with Arrays
int main()
{
int values[5]={0};
for (int i = 1; i < 5; i++){
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
i ( =5) < 5 is false. Exit the loop
animation
After the fourth iteration
0
1
2
3
4
0
1
3
6
10
-
8/7/2019 sa07slide(SingleDimensionalArray)
29/47
29
Trace Program with Arrays
int main()
{
int values[5]={0};
for (int i = 1; i < 5; i++){
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
After this line, values[0] is 11 (1 + 10)
0
1
2
3
4
11
1
3
6
10
animation
-
8/7/2019 sa07slide(SingleDimensionalArray)
30/47
30
Printing arrays
To print an array, you have to print each element in thearray using a loop like the following:
for (int i = 0; i < ARRAY_SIZE; i++){
cout
-
8/7/2019 sa07slide(SingleDimensionalArray)
31/47
31
Printing Character Array
For a character array, it can be printed using one printstatement. For example, the following code displaysDallas:
char city[] = "Dallas";
cout
-
8/7/2019 sa07slide(SingleDimensionalArray)
32/47
32
Copying Arrays
Can you copy array using a syntax like this?
list = myList;
This is not allowed in C++. You have to copy individualelements from one array to the other as follows:
for (int i = 0; i < ARRAY_SIZE; i++)
{
list[i] = myList[i];
}
-
8/7/2019 sa07slide(SingleDimensionalArray)
33/47
33
Summing All Elements
Use a variable named total to store the sum. Initially totalis 0. Add each element in the array to total using a looplike this:
double total = 0;
for (int i = 0; i < ARRAY_SIZE; i++)
{
total += myList[i];
}
-
8/7/2019 sa07slide(SingleDimensionalArray)
34/47
34
Finding the Largest Element
Use a variable named max to store the largest element.Initially max is myList[0]. To find the largest element inthe array myList, compare each element in myList withmax, update max if the element is greater than max.
double max = myList[0];
for (int i = 1; i < ARRAY_SIZE; i++)
{if (myList[i] > max) max = myList[i];
}
-
8/7/2019 sa07slide(SingleDimensionalArray)
35/47
35
Finding the smallest index of the
largest element
double max = myList[0];
int indexOfMax = 0;
for (int i = 1; i < ARRAY_SIZE; i++)
{if (myList[i] > max)
{
max = myList[i];
indexOfMax = i;
}
}
-
8/7/2019 sa07slide(SingleDimensionalArray)
36/47
36
Searching Arrays
Searching is the process of looking for a specific element inan array; for example, discovering whether a certain score isincluded in a list of scores. Searching is a common task incomputer programming. There are many algorithms anddata structures devoted to searching. In this section, two
commonly used approaches are discussed, linear search andbinary search.
int linearSearch(const int list[], int key, int arraySize)
{
for (int i = 0; i < arraySize; i++)
{if (key == list[i])
return i;
}
return-1;
}
list
key Compare key with list[i] for i = 0, 1,
[0] [1] [2]
-
8/7/2019 sa07slide(SingleDimensionalArray)
37/47
37
Linear Search
The linear search approach compares the key
element, key,sequentially with each element in
the array list. The method continues to do so
until the key matches an element in the list orthe list is exhausted without a match being
found. If a match is made, the linear search
returns the index of the element in the arraythat matches the key. If no match is found, the
search returns -1.
-
8/7/2019 sa07slide(SingleDimensionalArray)
38/47
38
Linear Search Animation
6 4 1 9 7 3 2 8
6 4 1 9 7 3 2 8
6 4 1 9 7 3 2 8
6 4 1 9 7 3 2 8
6 4 1 9 7 3 2 8
6 4 1 9 7 3 2 8
3
3
3
3
3
3
animation
Key List
-
8/7/2019 sa07slide(SingleDimensionalArray)
39/47
39
Binary Search
For binary search to work, the elements in the
array must already be ordered. Without loss of
generality, assume that the array is in
ascending order.e.g., 2 4 7 10 11 45 50 59 60 66 69 70 79
The binary search first compares the key with
the element in the middle of the array.
-
8/7/2019 sa07slide(SingleDimensionalArray)
40/47
40
Binary Search, cont.
If the key is less than the middle element,
you only need to search the key in the firsthalf of the array.
If the key is equal to the middle element,the search ends with a match.
If the key is greater than the middleelement, you only need to search the key inthe second half of the array.
Consider the following three cases:
-
8/7/2019 sa07slide(SingleDimensionalArray)
41/47
41
Binary Search
1 2 3 4 6 7 8 9
1 2 3 4 6 7 8 9
1 2 3 4 6 7 8 9
8
8
8
Key List
animation
-
8/7/2019 sa07slide(SingleDimensionalArray)
42/47
42
Binary Search, cont.
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
2 4 7 10 11 45 50 59 60 66 69 70 79
key is 11
key < 50
list
mid
[0] [1] [2] [3] [4] [5]
key > 7
key == 11
highlow
mid highlow
list
[3] [4] [5]
mid highlow
list
2 4 7 10 11 45
10 11 45
-
8/7/2019 sa07slide(SingleDimensionalArray)
43/47
43
Binary Search, cont.[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
2 4 7 10 11 45 50 59 60 66 69 70 79
key is 54
key > 50
list
mid
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
key < 66
key < 59
highlow
mid highlow
list
[7] [8]
mid highlow
list
59 60 66 69 70 79
59 60
[6] [7] [8]
highlow
59 60
-
8/7/2019 sa07slide(SingleDimensionalArray)
44/47
44
Binary Search, cont.
The binarySearch method returns the index of the
search key if it is contained in the list. Otherwise,
it returns insertion point - 1. The insertion point is
the point at which the key would be inserted into
the list.
-
8/7/2019 sa07slide(SingleDimensionalArray)
45/47
45
From Idea to Solutionint binarySearch(const int list[], int key, int arraySize)
{
int low = 0;
int high = arraySize - 1;
while (high >= low)
{
int mid = (low + high) / 2;
if (key < list[mid])high = mid - 1;
else if (key == list[mid])
return mid;
else
low = mid + 1;
}
return low - 1;
}
-
8/7/2019 sa07slide(SingleDimensionalArray)
46/47
46
Sorting Arrays
Sorting, like searching, is also a common task incomputer programming. It would be used, for
instance, if you wanted to display the grades from
Listing 6.2, AssignGrade.cpp, in alphabetical order.Many different algorithms have been developed for
sorting. This section introduces two simple, intuitive
sorting algorithms: selection sort and insertion sort.
-
8/7/2019 sa07slide(SingleDimensionalArray)
47/47
47
Selection sort finds the largest number in the list and places it last. It then finds the largestnumber remaining and places it next to last, and so on until the list contains only a singlenumber. Figure 6.17 shows how to sort the list {2, 9, 5, 4, 8, 1, 6} using selection sort.
Selection Sort
2 9 5 4 8 1 6
swap
Select 1 (the smallest) and swap it
with 2 (the first) in the list
1 9 5 4 8 2 6
swap
The number 1 is now in thecorrect position and thus no
longer needs to beconsidered.
1 2 5 4 8 9 6
swap
1 2 4 5 8 9 6
Select 2 (the smallest) and swap it
with 9 (the first) in the remaining
list
The number 2 is now in thecorrect position and thus no
longer needs to beconsidered.Select 4 (the smallest) and swap itwith 5 (the first) in the remaining
list
The number 6 is now in the
correct position and thus no
longer needs to beconsidered.
1 2 4 5 8 9 6Select 6 (the smallest) and swap itwith 8 (the first) in the remaining
list
1 2 4 5 6 9 8
swap
The number 6 is now in the
correct position and thus no
longer needs to beconsidered.
1 2 4 5 6 8 9
Select 8 (the smallest) and swap it
with 9 (the first) in the remaininglist
The number 8 is now in the
correct position and thus nolonger needs to beconsidered.
Since there is only one element
remaining in the list, sort is
completed
5 is the smallest and in the right
position. No swap is necessary
The number 5 is now in the
correct position and thus no
longer needs to beconsidered.
swap