Sie sind auf Seite 1von 23

CS304-Data Structures

Bishops University
Department of Computer Science

Slides 4: Arrays

M. ALLILI
A problem with simple variables

One variable holds one value

The value may change over time, but at any given time, a variable

holds a single value

If you want to keep track of many values, you need many variables

All of these variables need to have names

What if you need to keep track of hundreds or thousands of values?

1/23/2017 M. ALLILI, CS304 Slide 2


Multiple values

An array lets you associate one name with a fixed (but possibly large)
number of values

All values must have the same type

The values are distinguished by a numerical index between 0 and


array_size -1

0 1 2 3 4 5 6 7 8 9

myArray 12 43 6 83 14 -57 109 12 0 6

1/23/2017 M. ALLILI, CS304 Slide 3


Indexing into arrays

To reference a single array element, use array-name [ index ]

Indexed elements can be used just like simple variables

You can access their values

You can modify their values

An array index is sometimes called a subscript

1/23/2017 M. ALLILI, CS304 Slide 4


Using array elements

0 1 2 3 4 5 6 7 8 9

myArray 12 43 6 83 14 -57 109 12 0 6

Examples:

x = myArray[1]; // sets x to 43

myArray[4] = 99; // replaces 14 with 99

m = 5;
y = myArray[m]; // sets y to -57

z = myArray[myArray[9]]; // sets z to 109

1/23/2017 M. ALLILI, CS304 Slide 5


Array values

An array may hold any type of value, but...

all values in an array must be of the same type, and...

you must specify that type when you declare the array

For example, you can have:

an array of int (integers)

an array of strings (string is a built-in type in C++)

an array of Student (if Student is a class you have defined)

an array of arrays of strings

1/23/2017 M. ALLILI, CS304 Slide 6


Strings and arrays

strings and arrays both have special syntax

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:

int a[ ], b, c[ ], d; // notice position of brackets

a and c are int arrays

b and d are just ints

1/23/2017 M. ALLILI, CS304 Slide 7


Two ways to declare arrays

What does mean the following declaration:

double tab[8];

Allocates memory space for 8 doubles contiguously.

tab plays the role of a pointer containing the address of tab[0].

The allotted space is freed when tab goes out of scope.

We can use the following syntax:

tab[0]=5.3;

cout << tab[7];

We can also access to sub-arrays of tab such as (tab+2) as follows:

(tab + 2)[3] =12.; // equivalent to tab[5]=12.;

1/23/2017 M. ALLILI, CS304 Slide 8


Important jargon

We can use the dereferencing operator to access any element


of the array with the following syntax:

*tab equivalent to tab[0]

*(tab+1) equivalent to tab[1]

Passing an array as a parameter for a function consists only to


pass copy of the pointer:

void f(int []);

We can protect the array values by declaring the argument


constant:

void f(const int []);

1/23/2017 M. ALLILI, CS304 Slide 9


Example of array use I

Suppose you want to find the largest value in an array scores of 10


integers:

int largestScore = 0;

for (int i = 0; i < 10; i++) {

if (scores[i] > largestScore) {

largestScore = scores[i];

By the way, do you see an error in the above program?

What if all values in the array are negative?

1/23/2017 M. ALLILI, CS304 Slide 10


Example of array use II

To find the largest value in an array scores of 10 (possibly negative)


integers:

int largestScore = scores[0];

for (int i = 1; i < 10; i++) {

if (scores[i] > largestScore) {

largestScore = scores[i];

1/23/2017 M. ALLILI, CS304 Slide 11


Example of array use III

Suppose you want to find the largest value in an array scores and the
location in which you found that value:

int largestScore = scores[0];

int index = 0;

for (int i = 1; i < 10; i++) {

if (scores[i] > largestScore) {

largestScore = scores[i];

index = i;
}

1/23/2017 M. ALLILI, CS304 Slide 12


Arrays of arrays: Matrices

The elements of an array can be arrays

Once again, there is a special syntax

Declaration: int table[3][5];

Table of 3 rows and 5 columns

The first index (3) is usually called the row index; the second index (5)
is the column index

An array like this is called a two-dimensional array.

1/23/2017 M. ALLILI, CS304 Slide 13


Example array of arrays

int table[3][2]; or,


int table[ ][ ] = { {1, 2}, {3, 6}, {7, 8} };

For example, table[1][1] contains 6


table[2][1] contains 8, and
0 1
table[1][2] is array out of bounds
0 1 2 To zero out this table:
1 3 6 for (int i = 0; i < 3; i++) {
2 for (int j = 0; j < 2; j++) {
7 8 table[i][j] = 0;
}
}

1/23/2017 M. ALLILI, CS304 Slide 14


About sorted arrays

An array is sorted in ascending order if each element is no smaller than

the preceding element

An array is sorted in descending order if each element is no larger than

the preceding element

When we just say an array is sorted, we usually mean that it is sorted

in ascending order

1/23/2017 M. ALLILI, CS304 Slide 15


Searching an array of integers

If an array is not sorted, there is no better algorithm than linear search for
finding an element in it.

Example

int linearSearch(int target, int * a, n) {


for (int i = 0; i < n; i++) {
if (target == a[i]) return i;
}
return -1; // not a legal index
}

1/23/2017 M. ALLILI, CS304 Slide 16


Linear search takes linear time
Linear search has linear time complexity:
If the target (the thing we are looking for) is not in the array, we have to
look at all n elements

If the target is in the array, we have to look at n/2 elements on average

If we search an array that is twice as large, we have to look at twice as


many elements

For some constants k1 and k2, the time required to search the array is

T = k1 * n + k 2

for an array of size n

This is a linear equation

1/23/2017 M. ALLILI, CS304 Slide 17


Binary search

How do we look up a name in a phone book, or a word in a


dictionary?

Look somewhere in the middle

Compare whats there with the thing youre looking for

Decide which half of the remaining entries to look at next

Repeat until you find the correct place

This is the binary search algorithm

1/23/2017 M. ALLILI, CS304 Slide 18


Binary search

1/23/2017 M. ALLILI, CS304 Slide 19


Binary search

int binarySearch(int target, int * a, int n) {


int left =0, right= n-1;
while (left <= right) {
int middle = (left + right) / 2;
if (a[middle] == target) return middle ; // found
else if (a[middle] > target) right = middle 1;
else
left = middle + 1;
}
return -1; // -1 means "not found"
}

1/23/2017 M. ALLILI, CS304 Slide 20


Recursive binary search

int binarySearch(int target, int * a, int left, int right) {

if (left > right) return -1; // not found

int middle = (left + right) / 2;

if (a[middle] == target) return middle ; // found

else if (a[middle] > target)

return binarySearch(target, a, left, middle - 1);

else
return binarySearch(target, a, middle + 1, right);

1/23/2017 M. ALLILI, CS304 Slide 21


Binary search takes log n time

In binary search, we choose an index that cuts the remaining portion of

the array in half

We repeat this until we either find the value we are looking for, or we

reach a sub-array of size 1

If we start with an array of size n, we can cut it in half about log2n times

Hence, binary search has logarithmic (log n) time complexity

For an array of size 1000, this is 100 times faster than linear search (210

~= 1000)

1/23/2017 M. ALLILI, CS304 Slide 22


Conclusion
Linear search has linear time complexity

Binary search has logarithmic time complexity

For large arrays, binary search is far more efficient than linear search

However, binary search requires that the array be sorted

If the array is sorted, binary search is

100 times faster for an array of size 1000

50 000 times faster for an array of size 1 000 000

This is the kind of speedup that we care about when we analyze


algorithms

1/23/2017 M. ALLILI, CS304 Slide 23

Das könnte Ihnen auch gefallen