Professional Documents
Culture Documents
Lakshman Jayaratne
Topics Covered
Define and understand an ARRAY Initialising an array Searching an array
Definition of Array
An array is an indexed/subscripted list of elements of the same type (a homogeneous collection). 4
a[0]
21
a[1]
5
a[2]
3
a[3]
16 25 11 23
a[4] a[5] a[6] a[7]
2
a[8]
80
a[9]
Declaration: int a[10] Declare ten memory cells to store ten integers.
num[0] int num[1] int num[2] int num[3] int num[4] int num[5] int num[6] int num[7] int num[8] int num[9] int
4
cout << "Please input ten integers:\n"; for ( int i=0; i<= 9; i++){ cin >> num[i]; total = total + num[i]; } // end for
cout << "\n The total of the ten integers is " << total; } // end main
Compiler sets the size to match the number of elements in the list
Initialising an Array
? ? ? ? ? ? ? ? ?
scores int scores[9]; for (int i = 0; i <= 8; i++) { scores[i] = 0; } // end for
0 0 0 0 0 0 0 0 0
scores 6
Searching Problem
Given a collection of data, find a particular item in the collection. Store the data in an array Compare the search key with each element in the array. If there is a match, return the position of the element; Otherwise, the user can be informed of this fact. We call this algorithm Linear
Linear Search
a[0] a[1] a[2] a[3] a[n]
?
LookFor
Linear Search
a[0] a[1] a[2] a[3] a[i] a[n-1] a[n]
?
LookFor
10
Linear Search
a[0] a[1] a[2] a[3] a[i] a[n-1] a[n]
?
LookFor
11
Linear Search
a[0] a[1] a[2] a[3] a[i] a[n-1] a[n]
?
LookFor
12
13
15
9 10 4
Low index
High index
17
2
0
2
1
4
2
5
3
5
4
7
5
8
6
9 10
7 8
Look for 7
2
0
2
1
4
2
5
3
5
4
7
5
8
6
9 10
7 8
9 10
18
2
0
2
1
4
2
5
3
5
4
7
5
8
6
9 10
7 8
Look for 3
Low index
high index
2
Low index
2
1
4
2
5
3
5
high index
7
5
8
6
9 10
7 8
5
high index
9 10
19
Low index
while ((lowIndex <= highIndex) && (!found)) { lowindex highindex index = (lowIndex + highIndex) / 2; if (scores[index] == lookFor) found = true; lowindex highindex else if (lookFor < scores[index]) highIndex = index - 1; lowindex highindex else lowIndex = index + 1; } // end while if (found) return index; else return -1; } // end binarySearch
20
Walsh 99382103
23