Download presentation
Presentation is loading. Please wait.
1
Arrays
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.
3
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.
4
Examples Suppose Then the following are all legal array definitions.
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!
5
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 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)
6
// array of 10 uninitialized ints int A[10]; A[3] = 1; int x = A[3];
-- 1 A 4 5 6 3 2 8 9 7 A[4] A[5] A[6] A[3] A[0] A[2] A[8] A[9] A[7] A[1]
7
Jan, Feb, March, April, May, June, July, Aug., Sep., Oct., Nov. Dec.
quintilis sextilis septem octo novem decm Julius Casesar Augustus Julian calendar, Gregorian calendar
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
9
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]; int size=8; int A[size]; * Utilisation: int i; … A[i] …
10
Array Initialization 6 -1 int A[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
6 -1 Box A[3] 8 7 -1 9 A 4 3 2 5 1 6
11
If there are fewer values, the unspecified values are 0 (be careful!)
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 If no size, the compiler computes the size as the number of values int A[] = {1,2,3,4,5,6,7,8,9,10};
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
13
Arrays are ‘manipulated’ by loops
int A[10]; int i; i=0; while (i<10) { some actions on A[i]; i=i+1; }
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;
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!
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
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; }
18
Smallest 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; } Smallest
19
Put it into a function: How to pass an array?
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 SmallestValueSoFar, i; smallestvalue(A,10); } How to pass an array?
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)
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!
22
‘sub-array’ by defining a range
int A[10]; int myfunction(int A[], 4,7) Int myfunction(int A[], int sub, int sup)
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
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
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
26
Put it into a function: 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;
27
Concatenate two strings
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; // don’t forget the ending character s[j]=NULL; // j contains the length of s return j;
28
Put it into a function: 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;
29
Array applications Search and sorting:
the two most fundamental algorithms further systematically studied in comp171
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 }
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.
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 }
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;
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;
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; position = search(data,size,value); if(position==-1) cout << "Not found!!\n"; else cout << "Found at: " << position << endl;
36
Use ‘break’ or ‘return’
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; }
37
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
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
39
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.)
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.
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!
42
// 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; }
43
// 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) {
44
Put things together: 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; }
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.
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.
47
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
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; }
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; }
50
Multi-dimensional arrays
51
2-D Arrays // 2-D array of 30 uninitialized ints int A[3][10]; -- A 4
5 6 3 2 8 9 7 1
52
2-D Array References 'a' // 2-D array of 30 uninitialized chars
char A[3][10]; A[1][2] = ‘a’; char resp = A[1][2]; 'a' 1 2 3 4 5 6 7 8 9 A -- -- -- -- -- -- -- -- -- -- 1 -- -- ‘a’ -- -- -- -- -- -- -- 2 -- -- -- -- -- -- -- -- -- --
53
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)
54
Example of 2D 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] = …
55
C[i][j] = c[i][j]+A[i][k]*B[k][j]; }
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]; }
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);
57
Summary of arrays 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 * Declaration: int A[8]; or const int size=8; int A[size]; int size=8; int A[size]; * Utilisation: int i; … A[i] … * Loop: for (int i=0;i<size;i++) { … A[i] …} * Pass by reference: function(int A[], size) function(int B[][DIM], size)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.