Download presentation
Presentation is loading. Please wait.
2
Arrays
3
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.
4
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
5
Slide 4 Array Declaration and Definition * Syntax: [ ] int A[10]; The array elements are all values of the type The size of the array is indicated by, the number of elements in the array must be an int constant or a constant expression (at compilation). Note that it is possible for an array to have multiple dimensions.
6
Slide 5 Examples Suppose const 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 ints char B[MaxStringSize]; // array of 80 chars double C[M*N]; // array of 800 doubles int Values[MaxListSize];// array of 1000 ints Array dimensions have to be a constant, not a variable!
7
Slide 6 Array reference (decomposition) by subscripting (indexing) * 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 The expression in the brackets is known as the index n 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)
8
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]
9
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
10
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
11
Slide 10 Array Initialization int A[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; A[3] = -1; 876 9 A 432510 4 5 6 3 0 2 8 9 7 1 87 9 A 432510 4 5 6 3 0 2 8 9 7 1 Box A[3] 6
12
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};
13
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
14
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];
15
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
16
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!
17
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 Use a loop to consider each element in turn 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
18
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; }
19
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; }
20
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?
21
Slide 20 Array is passed by ‘reference’ * always passing two things: n array name n and array size (int) * All array elements are passed by reference (though the name is by value)
22
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!
23
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)
24
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
25
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
26
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
27
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:
28
Slide 27 char s1[100]=“…”; char s2[100]=“…”; char s[100]; // we construct s one character by one character, // start with copying s1 into s int j=0; while(s1[j] != NULL) { s[j]=s1[j]; j=j+1; } // then we copy s2 to s using k int k=0; while(s2[k] != NULL) { s[j]=s2[k]; k=k+1; j=j+1; } // don’t forget the ending character s[j]=NULL; // j contains the length of s return j; Concatenate two strings
29
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:
30
Multi-dimensional arrays
31
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
32
Slide 31 2-D Array References -- A 4 5 6 3 0 2 8 9 7 1 // 2-D array of 30 uninitialized chars char A[3][10]; A[1][2] = ‘a’; char resp = A[1][2]; --‘a’-- 0 2 1
33
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 n myfunction(int A[][5][5], int size)
34
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
35
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]; }
36
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*B prod(A,B,C,d); } Into a function:
37
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] …}
38
Array applications Search and sorting: - the two most fundamental algorithms - further systematically studied in comp171
39
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 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 } (related to ‘smallestvalue’ in the previous slides!)
40
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.
41
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 }
42
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; }
43
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; }
44
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:
45
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’
46
Slide 45 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
47
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
48
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.)
49
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.
50
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!
51
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 upper swap upper=upper-1; }
52
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) { }
53
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 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; } Put things together:
54
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.
55
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.
56
Slide 55 * Algorithm n 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: 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
57
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; }
58
Slide 57 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; } Put it into a function:
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.