arrays slide 2 arrays * an array is a collection of (homogeneous) data elements that are of the same...
Post on 20-Dec-2015
224 views
TRANSCRIPT
Slide 2
Arrays
An array is a collection of (homogeneous) data elements that are of the same type (e.g., a collection of integers,characters, doubles)
Arrays are like flats in abuilding, or post office boxes
Arrays provide a good way to name a collection, and to reference its individual elements.
Slide 3
Jan, Feb, March, April, May, June, July, Aug., Sep., Oct., Nov. Dec.
quintilis sextilis septem octo novem decm
1 2 3 4 5 6 7 8 9 10
Julius Casesar
Augustus
Julian calendar, Gregorian calendar
Slide 4
Array Declaration and Definition Syntax: <type> <arrayName>[<dimension>]
int A[10];
The array elements are all values of the type <type> The size of the array is indicated by <dimension>, the
number of elements in the array <dimension> must be an int constant or a constant
expression (at compilation). Note that it is possible for an array to have multiple dimensions.
Slide 5
Examples
Supposeconst int N = 20;const int M = 40;const int MaxStringSize = 80;const int MaxListSize = 1000;
Then the following are all legal array definitions.int A[10]; // array of 10 intschar B[MaxStringSize]; // array of 80 charsdouble C[M*N]; // array of 800 doublesint Values[MaxListSize];// array of 1000 ints
Array dimensions have to be a constant, not a variable!
Slide 6Array reference (decomposition)by subscripting (indexing)
Supposeint A[10]; // array of 10 ints
To access an individual element we must apply a subscript to list name A A subscript is a bracketed expression
The expression in the brackets is known as the index First element of list has index 0
A[0] Second element of list has index 1, and so on
A[1] Last element has an index one less than the size of the list
A[9]
Incorrect indexing is a common error (infinite loop is another one)
Slide 7
// array of 10 uninitialized ints
int A[10];
A[3] = 1;
int x = A[3];
-- -- 1--A -- -- ---- -- --
4 5 6 3 0 2 8 9 7 1
A[4] A[5] A[6]A[3]A[0] A[2] A[8]A[9]A[7]A[1]
Slide 8
Array Element Manipulation
Considerint A[10], i = 7, j = 2, k = 4;
A[0] = 1;
A[i] = 5;
A[j] = A[i] + 3;
A[j+1] = A[i] + A[0];
A[A[j]] = 12;
cin >> A[k]; // where the next input value is 3
-- 8 61AA[4] A[5] A[6]A[3]A[0] A[2] A[8] A[9]A[7]A[1]
-- -- 53 --12
Slide 9
Summary of arrays
* Declaration: int A[8];
or
const int size=8;
int A[size];
* Utilisation: int i;
… A[i] …
int size=8;
int A[size];
Collection of variables of the SAME type, of consecutive places:
Int A[8]; A[0], …, …, A[7], eight integer variables
Slide 10
Array Initialization
int A[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
A[3] = -1;
8 7 6 9A 4 3 25 1 0
4 5 6 3 0 2 8 9 7 1
8 7 -1 9A 4 3 25 1 0
4 5 6 3 0 2 8 9 7 1
Box A[3] 6 -1
Slide 11
If there are fewer values, the unspecified values are 0 (be careful!)
Compilation error if more values are given
If no size, the compiler computes the size as the number of values
int A[10] = {1,2,3,4,5};
int A[] = {1,2,3,4,5,6,7,8,9,10};
Slide 12
int a[5]={1,2}; // {1,2,0,0,0} int b[5]={}; // {0,0,0,0,0} int c[]={1,2,3}; // c[3]={1,2,3} int d[3]; // d[3] d[3]={5,6,7}; // wrong! int& e[]={1,2,3}; // wrong, no ‘reference’ array
Slide 13 Arrays are ‘manipulated’ by loops
int A[10];
int i;
i=0;while (i<10) {
some actions on A[i];i=i+1;
}
int A[10];
for (int i=0;i<10;i++) some actions on A[i];
Slide 14
// List A of n elements has already been set
const int n=100;int A[n];
int i=0;while(i<n) {
cout << A[i] << " ";i=i+1;
}cout << endl;
Example: displaying an array
Slide 15
Example of finding smallest value
Problem Find the smallest value in an array of integers
Input An array of integers of dimension N
Output The smallest value in the array
Note Array remains unchanged after finding the smallest
value!
Slide 16
Idea When looking for the smallest value, need a way of
remembering best candidate found so far
Design Search array looking for smallest value
Use a loop to consider each element in turn If current element is smallest so far, then update smallest
value so far
When done examining all of the elements, the smallest value seen so far is the smallest value
Slide 17
start with the first element (smallest the first element)
while (not yet the array end)
look at the current elementdoing something:
if (current < smallest)smallest current
go to the next element by i=i+1;}
Slide 18
const int N=10;int A[N]={……………};int SmallestValueSoFar, i;
SmallestValueSoFar = A[0];i=1;while(i<N) {
if (A[i] < SmallestValueSoFar)SmallestValueSoFar = A[i];
i=i+1;}
Slide 19
int smallest(int A[], int size) {
int smallestvalue,i;
smallestvalue = A[0];i=1;while(i<size) {
if (A[i] < smallestvalue)smallestvalue = A[i];
i=i+1;}return smallestvalue;
}
Put it into a function:
int main() {
const int N=10;
int A[N]={……………};
int SmallestValueSoFar, i;
smallestvalue(A,10);
}
How to pass an array?
Slide 20
Array is passed by ‘reference’
always passing two things: array name and array size (int)
All array elements are passed by reference (though the name is by value)
Slide 21
Use ‘const’ array to avoid modification
int smallest(const int A[], const int size) {
int smallestvalue,i;
smallestvalue = A[0];for (i=1; i<size; i++)
if (A[i] < smallestvalue)smallestvalue = A[i];
return smallestvalue;}
read-only, like CD ROM
can’t write on it!
Slide 22
‘sub-array’ by defining a range
int A[10];
int myfunction(int A[], 4,7)
Int myfunction(int A[], int sub, int sup)
Slide 23
‘segmentation fault’ error
compiler checks the constancy of the dimension But compiler can not check the index bound
It’s your responsability to ensure the right index range!!! Dont trespass into memory locations not belonging to you!
Int A[10];
A[-2]=5; // compilation is OK
A[100]=5; // no compilation error,
// but fatal run-time error:
// segmentation fault
Slide 24
C-string (not C++ string): array of characters
A 1D character array Null character ‘\0’ (ASCII code is 0 as well)
marks the end A length of N has ‘\0’ at N+1
Slide 25
Compute the length of a string
start from the first element, and increment the length by one each time we see a valid character
// j is the current length of the stringint j;
j=0; // start from 0while(s[j] != NULL-Character) {
j=j+1;}
j is the length
Slide 26
const char NULL=‘\0’;int length(const char s[]) {
int j=0;while(s[j] != NULL)
j=j+1;return j;
}
int main() { char A[20]=“Albert”; char B[20]=“Einstein”; cout << “length of A is” << length(A) << endl; cout << “length of B is” << length(B) << endl;
}
Put it into a function:
Slide 27
char s1[100]=“…”;char s2[100]=“…”;char s[100];
// we construct s one character by one character,
// start with copying s1 into sint j=0;while(s1[j] != NULL) {
s[j]=s1[j];j=j+1;
}
// then we copy s2 to s using kint k=0; while(s2[k] != NULL) {
s[j]=s2[k];k=k+1;j=j+1;
}// don’t forget the ending characters[j]=NULL;// j contains the length of sreturn j;
Concatenate two strings
Slide 28
int concatenate(const char s1[], const char s2[], char s[]) {int j=0;while(s[j] != NULL)
s[j]=s1[1];
int k=0;while(s2[k] != NULL) {
s[j]=s2[k];k=k+1;j=j+1;
}s[j]=NULL;return j;
}
int main() { char A[20]=“Albert”; char B[20]=“Einstein”; char C[20]; int l=concatenate(A,B,C); cout << “the concatenation of A and B is” << C << endl; cout << “length of C is” << l << endl;
}
Put it into a function:
Slide 30
2-D Arrays
// 2-D array of 30 uninitialized ints
int A[3][10];
-- -- ----
A
4 5 6 3 0 2 8 9 7 1
-- -- ---- -- --
-- -- ---- -- -- ---- -- --
-- -- ---- -- -- ---- -- -- 0
2
1
Slide 31
2-D Array References
-- -- ----
A
4 5 6 3 0 2 8 9 7 1
-- -- ---- -- --
// 2-D array of 30 uninitialized charschar A[3][10]; A[1][2] = ‘a’;char resp = A[1][2];
-- ‘a’ ---- -- -- ---- -- --
-- -- ---- -- -- ---- -- -- 0
2
1
Slide 32 N-dimensional array and 1D array
An array can be of any dimension, A[5][5][5] A N-dimension array is stored ‘row by row’ FORTRAN stores ‘column by column’ All other dimensions than the first one must
be specified in the function header myfunction(int A[][5][5], int size)
Slide 33
const int d=3; int A[d][d] = { {1, 5, 6}, {7, 9, 10}, {17, 30, 40} };
int B[d][d] = { {1, 2, 3}, {7, 9, 10}, {17, 30, 40} };
int C[d][d]; // C = A*B
for (i=0;i<d;i++) for (j=0;j<d;j++)
C[i][j] = …
Example of 2D array: matrix multiplication
Slide 34
const int d=3; int A[d][d] = { {1, 5, 6}, {7, 9, 10}, {17, 30, 40} };
int B[d][d] = { {1, 2, 3}, {7, 9, 10}, {17, 30, 40} };int C[d][d]; // C = A*B
for (i=0;i<d;i++) for (j=0;j<d;j++) {
C[i][j]=0;for (k=0;k<d;k++)
C[i][j] = c[i][j]+A[i][k]*B[k][j];}
Slide 35
void prod(int A[][3], int B[][3], int C[][3], int d) {int i,j,k;for (i=1;i<d;i++)
for (j=1;j<d;j++) {C[i][j]=0;for (k=1;k<d;k++)
C[i][j] = A[i][k]*B[k][j];}
}
int main() {
const int d=3; int A[d][d] = { {1, 5, 6}, {7, 9, 10}, {17, 30, 40} };
int B[d][d] = { {1, 2, 3}, {7, 9, 10}, {17, 30, 40} };int C[d][d]; // C = A*Bprod(A,B,C,d);
}
Into a function:
Slide 36
Summary of arrays
* Declaration: int A[8];
or
const int size=8;
int A[size];
* Utilisation: int i;
… A[i] …
int size=8;
int A[size];
Collection of variables of the SAME type, of consecutive places:
Int A[8]; A[0], …, …, A[7], eight integer variables
* Pass by reference: function(int A[], size)
function(int B[][DIM], size)
* Loop: for (int i=0;i<size;i++) { … A[i] …}
Array applications
Search and sorting: - the two most fundamental algorithms- further systematically studied in comp171
Slide 38
(Linear) Search (of unordered elements)
Search an (unordered) array of integers for a value and obtain its index if the value is found.
(the index value is -1 if the value is not found).
idea:
input: an integer array, and a given valueoutput: the position of the given value in the array if it exists, …
Start with the first elementwhile ((more elements)) {
check the current elementtry next element
}
(related to ‘smallestvalue’ in the previous slides!)
Slide 39
void main() { const int size=8; int data[size] = { 10, 7, 9, 1, 17, 30, 5, 6 };
int value, position; cout << "Enter search element: ";
cin >> value; position=-1; int n=0; while ( (n<size) ) {
if(data[n] == value) position=n; n=n+1;
} cout << "Found at: " << position << endl;
}
first version (not efficient)
Even we found earlier, we need to go through the entire array.
Slide 40
A better algorithm
Start from the first element, and Initialize things properly
while ((more elements) and (not yet found)) {
check the current element,
if it is the desired element,
keep the position and stop (as we found it!)
try next element
}
Slide 41
int main() { const int size=8; int data[size] = { 10, 7, 9, 1, 17, 30, 5, 6 };
int value; cout << "Enter search element: ";
cin >> value; bool found=false; int n=0; int position=-1; while ( (n<size) && (!found) ) {
if(data[n] == value) { found=true; position=n;} n=n+1;
}if(position==-1) cout << "Not found!!\n";else cout << "Found at: " << position << endl;
}
Slide 42
int main() { const int size=8; int data[size] = { 10, 7, 9, 1, 17, 30, 5, 6 };
int value; cout << "Enter search element: ";
cin >> value; bool found=false; int n=0; int position=-1; while ( (n<size) && (!found) ) {
if(data[n] == value) { found=true; position=n; break;} n=n+1;
}if(position==-1) cout << "Not found!!\n";else cout << "Found at: " << position << endl;
}
Slide 43
int search(const data[], const int size, const int value) { bool found=false; int n=0; int position=-1; while ( (n<size) && (!found) ) {
if(data[n] == value) { found=true; position=n;} n=n+1;
}return position;
}
int main() { const int size=8; int data[size] = { 10, 7, 9, 1, 17, 30, 5, 6 };
int value; cout << "Enter search element: ";
cin >> value; int position=-1;
position = search(data,size,value); if(position==-1) cout << "Not found!!\n"; else cout << "Found at: " << position << endl;
}
Put it into a function:
Slide 44
int search(const data[], const int size, const int value) { bool found=false; int n=0; int position=-1; while ( (n<size) && (!found) ) {
if(data[n] == value) { found=true; position=n;} n=n+1;
}return position;
}
int search(const data[], const int size, const int value) {
int n=0; int position=-1; while ( (n<size) ) {
if(data[n] == value) { found=true; position=n; return position;}
n=n+1;}
}
Use ‘break’ or ‘return’
Slide 45
Sorting To arrange a set of items in sequence. About 25~50% of all computing power is
used in sorting. Possible reasons:
Many applications require sorting Many applications perform sorting when they
don't have to Many applications use inefficient sorting
algorithms
Slide 46
Sorting Applications List of student ID names and numbers in a table
(sorted by name) List of scores before letter grade
assignment (sorted by students' scores) List of horses after a race (sorted by the
finishing times) To prepare an originally unsorted array for
ordered binary searching
Slide 47
Some Sorting Methods Selection sort
Bubble sort
Shell sort (a simple but faster sorting method; see p.331 of Numerical Recipes in C, 2nd ed., by William H. Press et al,
Cambridge University Press, 1992)
Quick sort (a much faster sorting method for most applications.)
Slide 48
Selection Sort Selection sort performs sorting by repeatedly
putting the largest element to the end of the unsorted part of the array until the whole array is sorted.
It is similar to the way that many people do their sorting.
Slide 49
Algorithm 1. Define the unsorted part of the array
as the entire array
2. While the unsorted part of the array has more than one element: Find its largest element (or smallest)
Swap with last element (or first for smallest)
Reduce unsorted part of the array by 1
Similar to the smallestvalue and search!
Slide 50
// work with sub-arrays from 0 to upper
upper = size-1;while(upper>0) {
find-the-maximum in the array from 0 to upperswap
upper=upper-1;}
Slide 51
// sort A[] from 0 to size-1// work with arrays A[] from 0 to upper
upper = size-1;while(upper>0) {
index=maximum(A,0,upper);swap(A[index],A[upper]);upper=upper-1;
}
int maximum(A,lower,upper) {
}void swap(int& x,int& y) {
}
Slide 52
const int size=9; int data[size]={ 10, 7, 9, 1, 9, 17, 30, 5, 6 };
int temp; // for swap int max_index; // index of max value
int size=9;
for(int upper=size-1; upper>0; upper--){// find largest itemmax_index = 0;for(int i=1; i<=upper; i++)
if(data[i] > data[max_index]) max_index = i;
// swap largest item with last item temp = data[max_index];
data[max_index] = data[upper];data[upper] = temp;
}
Put things together:
Slide 53
Bubble Sort
Bubble sort examines the array from start to finish, comparing two elements as it goes.
Any time it finds a larger element before a smaller element, it swaps the two.
In this way, the larger elements are passed towards the end.
The largest element of the array therefore "bubbles" to the end of the array.
It then repeats the process for the unsorted part of the array until the whole array is sorted.
Slide 54
Actually, each iteration of a ‘bubble sort’ is just an algorithm of finding the largest element!
This is how bubble sort got its name, because the smaller elements ‘float’ to the top, while the larger elements ‘sink’ to the bottom.
Slide 55
Algorithm Define the unsorted part of the array to be the entire array
While the unsorted part of the array has more than one element: 1. For every element in the unsorted part, swap with the next neighbor if it is larger than the neighbor
2. Reduce the unprocessed part of the array by 1
Slide 56
int temp;
for(upper=size-1;upper>0;upper--){for(i=0; i<upper; i++){
if(data[i] > data[i+1] ){ temp = data[i];
data[i] = data[i+1]; data[i+1] = temp; }
}}