Beruflich Dokumente
Kultur Dokumente
Bishops University
Department of Computer Science
Slides 4: Arrays
M. ALLILI
A problem with simple variables
The value may change over time, but at any given time, a variable
If you want to keep track of many values, you need many variables
An array lets you associate one name with a fixed (but possibly large)
number of values
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
Examples:
x = myArray[1]; // sets x to 43
m = 5;
y = myArray[m]; // sets y to -57
you must specify that type when you declare the array
strings are built in types which C++ provided as part of the Standard
Template Library (STL), and can be used with its special syntax (see
example).
You can declare more than one array variable in the same declaration:
double tab[8];
tab[0]=5.3;
int largestScore = 0;
largestScore = scores[i];
largestScore = scores[i];
Suppose you want to find the largest value in an array scores and the
location in which you found that value:
int index = 0;
largestScore = scores[i];
index = i;
}
The first index (3) is usually called the row index; the second index (5)
is the column index
in ascending order
If an array is not sorted, there is no better algorithm than linear search for
finding an element in it.
Example
For some constants k1 and k2, the time required to search the array is
T = k1 * n + k 2
else
return binarySearch(target, a, middle + 1, right);
We repeat this until we either find the value we are looking for, or we
If we start with an array of size n, we can cut it in half about log2n times
For an array of size 1000, this is 100 times faster than linear search (210
~= 1000)
For large arrays, binary search is far more efficient than linear search