Arrays Slide 2 Arrays An array is a

  • Slides: 57
Download presentation
Arrays

Arrays

Slide 2 Arrays * An array is a collection of (homogeneous) data elements that

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 a building, or post office boxes * Arrays provide a good way to name a collection, and to reference its individual elements.

Slide 3 Array Declaration and Definition * Syntax: <type> <array. Name>[<dimension>] int A[10]; The

Slide 3 Array Declaration and Definition * Syntax: <type> <array. Name>[<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 4 Examples * Suppose const * int int N = 20; M =

Slide 4 Examples * Suppose const * int int N = 20; M = 40; Max. String. Size = 80; Max. List. Size = 1000; Then the following are all legal array definitions. int A[10]; // char B[Max. String. Size]; // double C[M*N]; // int Values[Max. List. Size]; // array of of 10 ints 80 chars 800 doubles 1000 ints Array dimensions have to be a constant, not a variable!

Array reference (decomposition) by subscripting (indexing) Slide 5 * Suppose int A[10]; * //

Array reference (decomposition) by subscripting (indexing) Slide 5 * Suppose int A[10]; * // array of 10 ints To access an individual element we must apply a subscript to list name A n A subscript is a bracketed expression 1 The n expression in the brackets is known as the index First element of list has index 0 A[0] n Second element of list has index 1, and so on A[1] n 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 6 // array of 10 uninitialized ints int A[10]; A[3] = 1; int

Slide 6 // array of 10 uninitialized ints int A[10]; A[3] = 1; int x = A[3]; 0 A 1 2 3 4 5 6 7 8 9 -- --1 -- --- -A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]

Slide 7 Jan, Feb, March, April, May, June, July, Aug. , Sep. , Oct.

Slide 7 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 8 Array Element Manipulation * Consider int A[10], i = 7, j =

Slide 8 Array Element Manipulation * Consider int 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

Slide 9 Summary of arrays Collection of variables of the SAME type, of consecutive

Slide 9 Summary of arrays Collection of variables of the SAME type, of consecutive place Int A[8]; * Declaration: * Utilisation: A[0], …, …, A[7], eight integer variables int A[8]; or const int size=8; int A[size]; int i; … A[i] … int size=8; int A[size];

Slide 10 Array Initialization int A[10] = {9, 8, 7, 6, 5, 4, 3,

Slide 10 Array Initialization int A[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; 0 A 9 1 8 2 7 3 4 6 5 5 4 6 3 7 2 8 1 0 -1 6 Box A[3] 9 A[3] = -1; 0 A 9 1 8 2 7 3 -1 4 5 5 4 6 3 7 2 8 1 9 0

Slide 11 int A[10] = {1, 2, 3, 4, 5}; * If there are

Slide 11 int A[10] = {1, 2, 3, 4, 5}; * If there are fewer values, the unspecified values are 0 (be careful!) * Compilation error if more values are given int A[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; * If no size, the compiler computes the size as the number of values

Slide 12 * int a[5]={1, 2}; // {1, 2, 0, 0, 0} * int

Slide 12 * int a[5]={1, 2}; // {1, 2, 0, 0, 0} * int b[5]={}; // {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)

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; }

Slide 14 Example: displaying an array // List A of n elements has already

Slide 14 Example: displaying an array // 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;

Slide 15 Example of finding smallest value * Problem n Find the smallest value

Slide 15 Example of finding smallest value * Problem n Find the smallest value in an array of integers * Input n An array of integers of dimension N * Output n The smallest value in the array * Note n Array remains unchanged after finding the smallest value!

Slide 16 * Idea n When looking for the smallest value, need a way

Slide 16 * Idea n When looking for the smallest value, need a way of remembering best candidate found so far * Design n Search array looking for smallest value 1 Use a loop to consider each element in turn 1 If current element is smallest so far, then update smallest value so far n 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

Slide 17 start with the first element (smallest the first element) while (not yet the array end) look at the current element doing 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 Smallest. Value. So. Far, i; Smallest.

Slide 18 const int N=10; int A[N]={……………}; int Smallest. Value. So. Far, i; Smallest. Value. So. Far = A[0]; i=1; while(i<N) { if (A[i] < Smallest. Value. So. Far) Smallest. Value. So. Far = A[i]; i=i+1; }

Slide 19 Put it into a function: int smallest(int A[], int size) { int

Slide 19 Put it into a function: 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; } int main() { const int N=10; int A[N]={……………}; int Smallest. Value. So. Far, i; smallestvalue(A, 10); } How to pass an array?

Slide 20 Array is passed by ‘reference’ * always passing two things: array name

Slide 20 Array is passed by ‘reference’ * always passing two things: array name n and array size (int) n * 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

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)

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

Slide 23 ‘segmentation fault’ error compiler checks the constancy of the dimension * But compiler can not check the index bound * Int A[10]; A[-2]=5; // compilation is OK A[100]=5; // no compilation error, // but fatal run-time error: // segmentation fault * It’s your responsability to ensure the right index range!!! Dont trespass into memory locations not belonging to you!

Slide 24 *A C-string (not C++ string): array of characters 1 D character array

Slide 24 *A C-string (not C++ string): array of characters 1 D character array * Null character ‘’ (ASCII code is 0 as well) marks the end * A length of N has ‘’ at N+1

Slide 25 Compute the length of a string start from the first element, and

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 string int j; j=0; // start from 0 while(s[j] != NULL-Character) { j=j+1; } j is the length

Slide 26 Put it into a function: const char NULL=‘�’; int length(const char s[])

Slide 26 Put it into a function: const char NULL=‘’; 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; }

Slide 27 Concatenate two strings char s 1[100]=“…”; char s 2[100]=“…”; char s[100]; //

Slide 27 Concatenate two strings char s 1[100]=“…”; char s 2[100]=“…”; char s[100]; // we construct s one character by one character, // start with copying s 1 into s int j=0; while(s 1[j] != NULL) { s[j]=s 1[j]; j=j+1; } // then we copy s 2 to s using k int k=0; while(s 2[k] != NULL) { s[j]=s 2[k]; k=k+1; j=j+1; } // don’t forget the ending character s[j]=NULL; // j contains the length of s return j;

Slide 28 Put it into a function: int concatenate(const char s 1[], const char

Slide 28 Put it into a function: int concatenate(const char s 1[], const char s 2[], char s[]) { int j=0; while(s[j] != NULL) s[j]=s 1[1]; int k=0; while(s 2[k] != NULL) { s[j]=s 2[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; }

Array applications Search and sorting: - the two most fundamental algorithms - further systematically

Array applications Search and sorting: - the two most fundamental algorithms - further systematically studied in comp 171

Slide 30 (Linear) Search (of unordered elements) (related to ‘smallestvalue’ in the previous slides!)

Slide 30 (Linear) Search (of unordered elements) (related to ‘smallestvalue’ in the previous slides!) 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 value output: the position of the given value in the array if it exists, … Start with the first element while ((more elements)) { check the current element try next element }

Slide 31 first version (not efficient) void main() { const int size=8; int data[size]

Slide 31 first version (not efficient) 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; } Even we found earlier, we need to go through the entire array.

Slide 32 A better algorithm Start from the first element, and Initialize things properly

Slide 32 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 33 int main() { const int size=8; int data[size] = { 10, 7,

Slide 33 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 34 int main() { const int size=8; int data[size] = { 10, 7,

Slide 34 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 35 Put it into a function: int search(const data[], const int size, const

Slide 35 Put it into a function: 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; }

Slide 36 int search(const data[], const int size, const int value) { bool found=false;

Slide 36 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; } Use ‘break’ or ‘return’ 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; } }

Slide 37 Sorting *To arrange a set of items in sequence. *About 25~50% of

Slide 37 Sorting *To arrange a set of items in sequence. *About 25~50% of all computing power is used in sorting. *Possible reasons: n Many applications require sorting n Many applications perform sorting when they don't have to n Many applications use inefficient sorting algorithms

Slide 38 Sorting Applications * List of student ID names and numbers in a

Slide 38 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 39 Some Sorting Methods * Selection * Bubble * Shell sort (a simple

Slide 39 Some Sorting Methods * Selection * Bubble * Shell sort (a simple but faster sorting method; see p. 331 of Numerical Recipes in C, 2 nd ed. , by William H. Press et al, Cambridge University Press, 1992) * Quick sort (a much faster sorting method for most applications. )

Slide 40 Selection Sort * Selection sort performs sorting by repeatedly putting the largest

Slide 40 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 41 *Algorithm 1. Define the unsorted part of the array as the entire

Slide 41 *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 42 // work with sub-arrays from 0 to upper = size-1; while(upper>0) {

Slide 42 // work with sub-arrays from 0 to upper = size-1; while(upper>0) { find-the-maximum in the array from 0 to upper swap } upper=upper-1;

Slide 43 // sort A[] from 0 to size-1 // work with arrays A[]

Slide 43 // sort A[] from 0 to size-1 // work with arrays A[] from 0 to 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 44 Put things together: const int size=9; int data[size]={ 10, 7, 9, 17,

Slide 44 Put things together: const int size=9; int data[size]={ 10, 7, 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 item max_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;

Slide 45 Bubble Sort Bubble sort examines the array from start to finish, comparing

Slide 45 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 46 Actually, each iteration of a ‘bubble sort’ is just an algorithm of

Slide 46 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 47 * Algorithm Define the unsorted part of the array to be the

Slide 47 * Algorithm Define the unsorted part of the array to be the entire array n While the unsorted part of the array has more than one element: n 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 48 int temp; for(upper=size-1; upper>0; upper--){ for(i=0; i<upper; i++){ if(data[i] > data[i+1] ){

Slide 48 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; } } }

Slide 49 Put it into a function: void sort(int data[], int size) { int

Slide 49 Put it into a function: void sort(int data[], int size) { int upper, 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; } }

Multi-dimensional arrays

Multi-dimensional arrays

Slide 51 2 -D Arrays // 2 -D array of 30 uninitialized ints int

Slide 51 2 -D Arrays // 2 -D array of 30 uninitialized ints int A[3][10]; A 0 1 2 3 4 5 6 7 8 9 ---- ---- ----

Slide 52 2 -D Array References // 2 -D array of 30 uninitialized chars

Slide 52 2 -D Array References // 2 -D array of 30 uninitialized chars char A[3][10]; A[1][2] = ‘a’; char resp = A[1][2]; A 0 1 2 0 1 ---- 2 3 4 5 6 7 8 9 -- -‘a’ --- -- ---- ----

Slide 53 N-dimensional array and 1 D array * An array can be of

Slide 53 N-dimensional array and 1 D 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 n myfunction(int A[][5][5], int size)

Slide 54 Example of 2 D array: matrix multiplication const int d=3; int A[d][d]

Slide 54 Example of 2 D array: matrix multiplication 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] = …

Slide 55 const int d=3; int A[d][d] = { {1, 5, 6}, {7, 9,

Slide 55 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 56 Into a function: void prod(int A[][3], int B[][3], int C[][3], int d)

Slide 56 Into a function: 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*B prod(A, B, C, d); }

Slide 57 Summary of arrays Collection of variables of the SAME type, of consecutive

Slide 57 Summary of arrays Collection of variables of the SAME type, of consecutive places: Int A[8]; A[0], …, …, A[7], eight integer variables * Declaration: int A[8]; or const int size=8; int A[size]; * Utilisation: int i; … A[i] … int size=8; int A[size]; * Loop: for (int i=0; i<size; i++) { … A[i] …} * Pass by reference: function(int A[], size) function(int B[][DIM], size)