Arrays - PowerPoint PPT Presentation

1 / 57
About This Presentation
Title:

Arrays

Description:

comp104 notes - UNSW School of Computer Science and ... ... Arrays – PowerPoint PPT presentation

Number of Views:257
Avg rating:3.0/5.0
Slides: 58
Provided by: ust110
Category:

less

Transcript and Presenter's Notes

Title: Arrays


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
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
4
Array Declaration and Definition
  • Syntax
  • lttypegt ltarrayNamegtltdimensiongt
  • int A10
  • The array elements are all values of the type
    lttypegt
  • The size of the array is indicated by
    ltdimensiongt, the number of elements in the array
  • ltdimensiongt must be an int constant or a constant
    expression (at compilation). Note that it is
    possible for an array to have multiple
    dimensions.

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 A10 // array of 10 ints
  • char BMaxStringSize // array of 80 chars
  • double CMN // array of 800 doubles
  • int ValuesMaxListSize// array of 1000 ints

Array dimensions have to be a constant, not a
variable!
6
Array reference (decomposition)by subscripting
(indexing)
  • Suppose
  • int A10 // 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
  • A0
  • Second element of list has index 1, and so on
  • A1
  • Last element has an index one less than the size
    of the list
  • A9
  • Incorrect indexing is a common error (infinite
    loop is another one)

7
  • // array of 10 uninitialized ints
  • int A10
  • A3 1
  • int x A3

8
Array Element Manipulation
  • Consider
  • int A10, i 7, j 2, k 4
  • A0 1
  • Ai 5
  • Aj Ai 3
  • Aj1 Ai A0
  • AAj 12
  • cin gtgt Ak // where the next input value is 3

9
Summary of arrays
Collection of variables of the SAME type, of
consecutive places Int A8
? A0, , , A7, eight integer variables
Declaration int A8
or const int size8
int Asize
int size8 int Asize
Utilisation int i
Ai
10
Array Initialization
  • int A10 9, 8, 7, 6, 5, 4, 3, 2, 1, 0
  • A3 -1

Box A3
11
int A10 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 a51,2 // 1,2,0,0,0
  • int b5 // 0,0,0,0,0
  • int c1,2,3 // c31,2,3
  • int d3 // d3
  • d35,6,7 // wrong!
  • int e1,2,3 // wrong, no reference array

13
Arrays are manipulated by loops
  • int A10
  • int i
  • i0
  • while (ilt10)
  • some actions on Ai
  • ii1

int A10 for (int i0ilt10i) some
actions on Ai
14
Example displaying an array
  • // List A of n elements has already been set
  • const int n100
  • int An
  • int i0
  • while(iltn)
  • cout ltlt Ai ltlt " "
  • ii1
  • cout ltlt 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 lt smallest)
  • smallest ? current
  • go to the next element by ii1

18
  • const int N10
  • int AN
  • int SmallestValueSoFar, i
  • SmallestValueSoFar A0
  • i1
  • while(iltN)
  • if (Ai lt SmallestValueSoFar)
  • SmallestValueSoFar Ai
  • ii1
  • Smallest

19
Put it into a function
  • int smallest(int A, int size)
  • int smallestvalue,i
  • smallestvalue A0
  • i1
  • while(iltsize)
  • if (Ai lt smallestvalue)
  • smallestvalue Ai
  • ii1
  • return smallestvalue

int main() const int N10 int
AN 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
A0 for (i1 iltsize i) if (Ai lt
smallestvalue) smallestvalue Ai return
smallestvalue
read-only, like CD ROM cant write on it!
22
sub-array by defining a range
int A10 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
  • Its your responsability to ensure the right
    index range!!! Dont trespass into memory
    locations not belonging to you!

Int A10 A-25 // compilation is
OK A1005 // 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 N1

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 j0 // start from 0 while(sj
! NULL-Character) jj1 j is the
length
26
Put it into a function
const char NULL\0 int length(const char s)
int j0 while(sj ! NULL)
jj1 return j int main() char
A20Albert char B20Einstein cout
ltlt length of A is ltlt length(A) ltlt endl cout
ltlt length of B is ltlt length(B) ltlt endl
27
Concatenate two strings
char s1100 char s2100 char
s100 // we construct s one character by one
character, // start with copying s1 into
s int j0 while(s1j ! NULL)
sjs1j jj1 // then we copy s2
to s using k int k0 while(s2k ! NULL)
sjs2k kk1 jj1 // dont
forget the ending character sjNULL // 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 j0 while(sj ! NULL)
sjs11 int k0 while(s2k ! NULL)
sjs2k kk1 jj1 sjNULL
return j int main() char
A20Albert char B20Einstein char
C20 int lconcatenate(A,B,C) cout ltlt the
concatenation of A and B is ltlt C ltlt endl cout
ltlt length of C is ltlt l ltlt endl
29
  • Multi-dimensional arrays

30
2-D Arrays
  • // 2-D array of 30 uninitialized ints
  • int A310

31
2-D Array References
  • // 2-D array of 30 uninitialized chars
  • char A310
  • A12 a
  • char resp A12

4
5
6
3
0
2
8
9
7
1
A
--
--
--
--
--
--
--
--
--
--
0
--
a
--
--
--
--
--
--
--
--
1
--
--
--
--
--
--
--
--
--
--
2
32
N-dimensional array and 1D array
  • An array can be of any dimension, A555
  • 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 A55, int size)

33
Example of 2D array matrix multiplication
  • const int d3
  • int Add 1, 5, 6, 7, 9, 10, 17,
    30, 40
  • int Bdd 1, 2, 3, 7, 9, 10, 17, 30,
    40
  • int Cdd // C AB
  • for (i0iltdi)
  • for (j0jltdj)
  • Cij

34
  • const int d3
  • int Add 1, 5, 6, 7, 9, 10, 17,
    30, 40
  • int Bdd 1, 2, 3, 7, 9, 10, 17, 30,
    40
  • int Cdd // C AB
  • for (i0iltdi)
  • for (j0jltdj)
  • Cij0
  • for (k0kltdk)
  • Cij cijAikBkj

35
Into a function
  • void prod(int A3, int B3, int C3,
    int d)
  • int i,j,k
  • for (i1iltdi)
  • for (j1jltdj)
  • Cij0
  • for (k1kltdk)
  • Cij AikBkj
  • int main()
  • const int d3
  • int Add 1, 5, 6, 7, 9, 10, 17,
    30, 40
  • int Bdd 1, 2, 3, 7, 9, 10, 17, 30,
    40
  • int Cdd // C AB
  • prod(A,B,C,d)

36
Summary of arrays
Collection of variables of the SAME type, of
consecutive places Int A8
? A0, , , A7, eight integer variables
Declaration int A8
or const int size8
int Asize
int size8 int Asize
Utilisation int i
Ai
Loop for (int i0iltsizei) Ai
Pass by reference function(int A,
size)
function(int BDIM, size)
37
  • Array applications
  • Search and sorting
  • the two most fundamental algorithms
  • further systematically studied in comp171

38
(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

39
first version (not efficient)
  • void main()
  • const int size8
  • int datasize 10, 7, 9, 1, 17, 30, 5, 6
  • int value, position
  • cout ltlt "Enter search element "
  • cin gtgt value
  • position-1
  • int n0
  • while ( (nltsize) )
  • if(datan value) positionn
  • nn1
  • cout ltlt "Found at " ltlt position ltlt endl

Even we found earlier, we need to go through the
entire array.
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

41
  • int main()
  • const int size8
  • int datasize 10, 7, 9, 1, 17, 30, 5, 6
  • int value
  • cout ltlt "Enter search element "
  • cin gtgt value
  • bool foundfalse
  • int n0
  • int position-1
  • while ( (nltsize) (!found) )
  • if(datan value) foundtrue positionn
  • nn1
  • if(position-1) cout ltlt "Not found!!\n"
  • else cout ltlt "Found at " ltlt position ltlt endl

42
  • int main()
  • const int size8
  • int datasize 10, 7, 9, 1, 17, 30, 5, 6
  • int value
  • cout ltlt "Enter search element "
  • cin gtgt value
  • bool foundfalse
  • int n0
  • int position-1
  • while ( (nltsize) (!found) )
  • if(datan value) foundtrue positionn
    break
  • nn1
  • if(position-1) cout ltlt "Not found!!\n"
  • else cout ltlt "Found at " ltlt position ltlt endl

43
Put it into a function
  • int search(const data, const int size, const
    int value)
  • bool foundfalse
  • int n0
  • int position-1
  • while ( (nltsize) (!found) )
  • if(datan value) foundtrue positionn
  • nn1
  • return position
  • int main()
  • const int size8
  • int datasize 10, 7, 9, 1, 17, 30, 5, 6
  • int value
  • cout ltlt "Enter search element "
  • cin gtgt value
  • int position-1

44
  • int search(const data, const int size, const
    int value)
  • bool foundfalse
  • int n0
  • int position-1
  • while ( (nltsize) (!found) )
  • if(datan value) foundtrue positionn
  • nn1
  • return position

Use break or return
int search(const data, const int size, const
int value) int n0 int position-1
while ( (nltsize) ) if(datan value)
foundtrue positionn return position
nn1
45
Sorting
  • To arrange a set of items in sequence.
  • About 2550 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

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

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.)

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.

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!
50
  • // work with sub-arrays from 0 to upper
  • upper size-1
  • while(uppergt0)
  • find-the-maximum in the array from 0 to upper
  • swap
  • upperupper-1

51
  • // sort A from 0 to size-1
  • // work with arrays A from 0 to upper
  • upper size-1
  • while(uppergt0)
  • indexmaximum(A,0,upper)
  • swap(Aindex,Aupper)
  • upperupper-1
  • int maximum(A,lower,upper)
  • void swap(int x,int y)

52
Put things together
  • const int size9
  • int datasize 10, 7, 9, 1, 9, 17, 30, 5, 6
  • int temp // for swap
  • int max_index // index of max value
  • int size9
  • for(int uppersize-1 uppergt0 upper--)
  • // find largest item
  • max_index 0
  • for(int i1 iltupper i)
  • if(datai gt datamax_index) max_index
    i
  • // swap largest item with last item
  • temp datamax_index
  • datamax_index dataupper
  • dataupper temp

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.

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.
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

56
  • int temp
  • for(uppersize-1uppergt0upper--)
  • for(i0 iltupper i)
  • if(datai gt datai1 )
  • temp datai
  • datai datai1
  • datai1 temp

57
Put it into a function
  • void sort(int data, int size)
  • int upper,temp
  • for(uppersize-1uppergt0upper--)
  • for(i0 iltupper i)
  • if(datai gt datai1 )
  • temp datai
  • datai datai1
  • datai1 temp
Write a Comment
User Comments (0)
About PowerShow.com