Click here to load reader

One-Dimensional and Multi-Dimensional Arrays, Searching & Sorting, Parameter passing to Functions Array Data Structures & Algorithms

Embed Size (px)

Citation preview

  • Slide 1
  • One-Dimensional and Multi-Dimensional Arrays, Searching & Sorting, Parameter passing to Functions Array Data Structures & Algorithms
  • Slide 2
  • Concepts of Data Collections Arrays in C Syntax Usage Array based algorithms
  • Slide 3
  • Concepts of Data Collections Sets, Lists, Vectors, Matrices and beyond
  • Slide 4
  • Sets & Lists The human language concept of a collection of items is expressed mathematically using Sets Sets are not specifically structured, but structure may be imposed on them Sets may be very expressive but not always easily represented Example: The set of all human emotions. Lists are representations of sets that simply list all of the items in the set Lists may be ordered or unordered. Some useful lists include data values and the concept of position within the list. Example representations: { 0, 5, -2, 4 } { TOM, DICK } First Second
  • Slide 5
  • Vectors, Matrices and beyond Many examples of lists arise in mathematics and they provide a natural basis for developing programming syntax and grammar Vectors are objects that express the notion of direction and size (magnitude) The 3-dimensional distance vector D has components { D x, D y, D z } along the respective x, y and z axes, with magnitude D = sqrt(D x 2 +D y 2 +D z 2 ) We use descriptive language terminology such as The xth component of D... Or, D-sub-x
  • Slide 6
  • Vectors, Matrices and beyond Higher dimensional objects are often needed to represent lists of lists. Matrices are one example that sometimes can be represented in tabular form 2-dimensional tables (row, column) 3- and higher are hard to visualize, but are meaningful Beyond this, mathematics works with objects called tensors and groups (and other entities), and expresses the access to object members (data values) using properties and indices based on topologies (loosely put, shape structures)
  • Slide 7
  • Vectors, Matrices and beyond In this course we focus on an introduction to the basic properties and algorithms associated with vectors and matrices, and lists (later) These objects are mathematically defined as ordered, structured lists The ordering derives from the property that each element of the list exists at a specific position Enumerated starting at 0 and incrementing by 1 to a maximum value The structure determines the mechanism and method of access to the list and its member elements
  • Slide 8
  • Arrays in C Syntax Memory structure Usage Functions
  • Slide 9
  • Arrays in C Syntax How to declare and reference 1D arrays using subscript notation Memory structure How is RAM allocated the meaning of direct access through subscripting Usage Some simple illustrative examples Functions How to deal with arrays as function arguments
  • Slide 10
  • Arrays in C - Syntax Consider the array declarations int StudentID [ 1000 ] ; float Mark [ 1000 ] ; char Name [ 30 ] ; Each of the declarations defines a storage container for a specific maximum number of elements Up to 1000 Student (integer) ID values Up to 1000 (real) Marks A Name of up to 30 characters
  • Slide 11
  • Arrays in C - Syntax Each array is referred to by its declared name float A [ 100 ] ;... where A refers to the entire collection of 100 storages On the other hand, each separate element of A is referenced using the subscript notation A[0] = 12.34 ; /* assign 12.34 to the first element */ /* NOTE: subscripts always start from 0 */ A[K] = 0.0 ; /* assign 0 to the (K+1)th element */ Note: Although a bit clumsy in human natural language, we can change our use of language so that A[K] always refers to the Kth element (not K+1), always starting from 0 as the 0th element.
  • Slide 12
  • Arrays in C - Syntax It is not necessary to initialize or reference all elements of an array in a program Unlike scalar variables declared as primitive data types, these uninitialized, non-referenced array elements are not flagged as warnings by the compiler There are good reasons to declare arrays of larger size than might be required in a particular execution run of a program At the outset, design the program to accommodate various sizes of data sets (usually acquired as input), up to a declared maximum size This avoids the need to modify and recompile the program each time it is used.
  • Slide 13
  • Arrays in C - Syntax This is a good time to introduce another compiler pre- processor directive, #define: #define is used to define constant expression symbols in C programs. The value of such symbols is that they localize positions of program modification. Example: #define MAX_SIZE 1000 int main ( ) { int SID [ MAX_SIZE ] ; float Mark [ MAX_SIZE ] ;..... } #define directives are normally located at the beginning of the program source code, after #include directives, and before function prototypes and the main function. In the example, by using the defined symbol MAX_SIZE, changes to SID and Mark array sizes can be accomplished by simply changing the value assigned to MAX_SIZE and recompiling.
  • Slide 14
  • Arrays in C Memory structure Now consider the declaration int A [ 9 ] ; The entire allocation unit is called A the array name There must be 9 integer sized allocations in RAM Each element is located contiguously (in sequence and touching) RAM AA[0] A[8]
  • Slide 15
  • Arrays in C Memory structure Arrays are often called direct access storage containers The reference to A[K] is translated by the compiler to First, calculate the relative address offset K * sizeof int Second, add RAO to base address of A, or simply &A[0] &A[K] == &A[0] + K*sizeof int RAM A[0] A[ K ] sizeof int RAO Direct Access :: Since the cost of the address computation is always the same (constant) and it provides the actual RAM address location where the data is stored. The sizeof, operator is a compile-time operator (not an executable instruction or operator) that determines the RAM storage size allocated to a data structure. When sizeof is applied to a primitive data type, it provides the size of allocated storage, in bytes. Try running a program with statements such as: printf( The size of int is %d bytes\n, sizeof int ) ; 01K01K
  • Slide 16
  • Arrays in C Usage Referencing arrays is straightforward using the subscript notation B = A[ 5 ] ; /* assign 6 th element of A to B */ A [ J ] < A [ K ] /* relational expression */ B = 0.5*( A[J] A[J-1] ); /* finite difference */ printf( %d %d %d\n, A[0], A[mid], A[N-1] ) ; scanf ( %d%lf%lf, &N, &R[K], R ) ; /* Note */
  • Slide 17
  • Arrays in C Average vs Median Problem: Input N real numbers and find their average and median. Assume the values are already sorted from lowest to highest Assume no more than 1000 values will be inputted Solution: Declarations float X [1000], Sum, Ave, Median ; int N, Mid ;
  • Slide 18
  • Arrays in C Average vs Median Declarations float A [1000], Sum = 0.0, Ave, Median ; int N, Mid, K ; Input Data printf( Enter number of values in list ) ; scanf( %d, &N ) ; /* Enter all real values into array X */ for( K=0; K < N; K++ ) { scanf( %f, &A[K] ) ; /* NOTE: & must be used */ Sum += A[K] ; }
  • Slide 19
  • Arrays in C Average vs Median Compute Average and Median Ave = Sum / (float) N ; /* real division */ Mid = N / 2 ; /* (integer) midpoint of list */ Median = A [ Mid ] ; Report results printf( Average = %, Ave ); printf( Median = %f\n, Median );
  • Slide 20
  • Arrays in C Related arrays Problem: Obtain student marks from testing and store the marks along with ID numbers Assume marks are float and IDs are int data types Solution Related arrays Define two arrays, one for IDs and one for marks int SID [ 100 ] ; float Mark [ 100 ] ; Coordinate input of data (maintain relationships) for( K = 0 ; K < N ; K++ ) scanf( %d%f, &SID[K], &Mark[K] ) ;
  • Slide 21
  • Arrays in C Functions Passing arrays as parameters in functions requires some care and some understanding. We begin with an example. Calculate the dot product of two 3-vectors U and V. Components: U[0], U[1], U[2] V[0], V[1], V[2] Mathematics: The dot product is defined as DotProd( U, V ) ::= U[0]*V[0] + U[1]*V[1] + U[2]*V[2] Since the dot product operation is required often, it would make a useful function. U V U. V
  • Slide 22
  • Arrays in C Functions Solution function: double DotProd3 ( double U[3], double V[3] ) { return U[0] * V[0] + U[1] * V[1] + U[2] * V[2] ; } Note the arguments which specify that arrays of type double with exactly three (3) elements will be passed. Note that the limitation to 3 elements is reflected in the design of the function name: DotProd3
  • Slide 23
  • Arrays in C Functions Extend this to dot product of N-dimensional vectors: double DotProdN ( double U[ ], double V[ ], int N ) { double DPN = 0.0 ; int K ; for( K = 0 ; K < N ; K++ ) DPN += U[K] * V[K] ; return DPN ; } Note the array arguments do not specify a maximum array size. This provides flexibility of design since now the function can handle any value of N. It is up to the programmer to ensure that the actual input arrays and N conform to the assumptions.
  • Slide 24
  • Arrays in C Functions An alternative to the same code is to use pointer references: double DotProdN ( double * U, double * V, int N ) { double DPN = 0.0 ; int K ; for( K = 0 ; K < N ; K++ ) DPN += U[K] * V[K] ; return DPN ; } Note the array arguments are now expressed as pointer references. This maintains the same flexibility as previously.
  • Slide 25
  • Arrays in C Functions A final alternative to the same code is to use pointer references altogether: double DotProdN ( double * U, double * V, int N ) { double DPN = 0.0 ; int K ; for( K = 0 ; K < N ; K++, U++, V++ ) DPN += *U * *V ; return DPN ; } The U and V variables are address pointers to the array components. U++ and V++ perform the action of updating the pointers by an amount equal to the size of the array data type (in this case double is usually 8 bytes), thus pointing to the next array component in sequence. Pointers are not the same as ints ! If A is an int (say, 5), then A++ always evaluates to the next (or successor) value in sequence (ie. 6). On the other hand, if P is a pointer (say, int *, with value &A[K]), then P++ evaluates to the next (or successor) value in sequence, which is usually the next element of an array (ie. &A[K=1]).
  • Slide 26
  • Arrays in C Functions The previous examples have illustrated the various ways that are used to pass array arguments to functions. double DotProd3 ( double U[3], double V[3] ); double DotProdN ( double U[ ], double V[ ], int N ); double DotProdN ( double * U, double * V, int N ); There are important differences When the size of the array is specified explicitly (eg. double U[3]), some C compilers will allocate storage space for all array elements within the function stack frame If arrays are declared within the function body, they are almost always allocated within the stack frame When the array size is not stated explicitly, a pointer to the array is allocated (much smaller in size than the entire array)
  • Slide 27
  • Arrays in C Functions C compilers may perform code and storage optimization Create the most efficient executable code Create the most efficient use of RAM storage By allocating array storage within stack frames, a significant amount of wasted space occurs due to avoidable duplication of storage allocations It also follows that a wastage of time occurs since it is necessary to copy data from arrays declared in the calling point code to arrays declared in the called point. Pointers solve most of these problems (with a small, but acceptable, increase in processing time) Optimization is a difficult problem and is still the subject of much research
  • Slide 28
  • Array Based Algorithms Searching Sorting
  • Slide 29
  • Array Based Algorithms Searching How to locate items in a list Simplicity versus speed and list properties Sorting Putting list elements in order by relative value Promoting efficient search
  • Slide 30
  • Search Algorithms Searching is a fundamentally important part of working with arrays Example: Given a student ID number, what is the Mark they obtained on the test? Do this for all students who enquire. Constructing a good, efficient algorithm to perform the search is dependent on whether the IDs are in random order or sorted. Random order use sequential search Sorted order use divide-and-conquer approach
  • Slide 31
  • Search Algorithms - Random If a list is stored in random order a possible search technique is to look at the list elements in random order search int srchID, K ; printf( Enter your SID ) ; scanf( %d, &srchID ) ; for( K=rand() % N ; srchID != SID[ K ] ; K=rand() % N ) ; printf( SID = %d, Mark = %f\n, SID[K], Mark[K] ); PROBLEM 1: No guarantee that rand() will produce a result and exit the for loop, especially if the item does not exist. PROBLEM 2: It is possible that an array element position will be accessed that has not had data stored (will stop the program as an error uninitialized data access violation).
  • Slide 32
  • Search Algorithms - Linear If a list is stored in random order a better search technique is to look at the list elements in order, from the beginning of the list until the element is found or the list elements are exhausted int srchID, K, N = 100 ; /* Assume 100 elements */ printf( Enter your SID ) ; scanf( %d, &srchID ) ; /* Perform the search */ for( K=0; KN ? ) Sequential (Linear)O( N ) Divide & Conquer (Binary)O( log N ) In the best case, any search algorithm may be successful after only one (1) probe Usually, one is interested in worst case and average case in choosing an algorithm. N
  • Slide 45
  • Sorting Algorithms.... Putting things in order........ order things Putting in....
  • Slide 46
  • Sorting Algorithms From our discussion of binary search we understand the need for the data to be ordered within lists in order to promote fast searching using Binary Search It is also important to understand that not every list should be sorted study each case carefully Sorting algorithms are designed to perform the ordering required There are literally hundreds of specialized sorting algorithms, with varying efficiencies We will focus on a sorting algorithm called Selection Sort
  • Slide 47
  • Sorting Algorithms - Selection Selection Sort relies on being able to find the largest (or smallest) element in a sublist Each time the proper value is found, it is exchanged with the element at the end of the sublist We re-apply this technique by shrinking the size of the sublist, until there is no remaining sublist (or a sublist of size 1 element which is already sorted). We consider the example.......... 82 45 31 72 56 62 87 90
  • Slide 48
  • Sorting Algorithms - Selection 82 45 31 72 56 62 87 90 82 45 31 72 56 62 87 90 82 45 31 72 56 62 87 90 62 45 31 72 56 82 87 90 62 45 31 72 56 82 87 90 62 45 31 56 72 82 87 90 1234
  • Slide 49
  • Sorting Algorithms - Selection 56 45 31 62 72 82 87 90 31 45 56 62 72 82 87 90 31 45 56 62 72 82 87 90 62 45 31 56 72 82 87 90 56 45 31 62 72 82 87 90 31 45 56 62 72 82 87 90 5867
  • Slide 50
  • Sorting Algorithms - Selection From the example we note that the final step 8 is not actually required, since a sub-list of one (1) element is automatically sorted (by definition). Hence, it took 7 steps to complete the sort. In general, for a list of size N elements, it takes N-1 steps. Each step consists of two parts: First, search an unordered sub-list for the largest element The size of the sub-list is N-K for step K (starting from K=0) Second, exchange (swap) the largest element with the last element in the sub-list Upon completion of each step it should be noted that the sorted sub-list grows by one element while the unsorted sub-list shrinks by one element.
  • Slide 51
  • Sorting Algorithms - Selection Start with a sub-list of N unsorted values, and a sub-list of 0 sorted values. The unsorted sub-list has subscripts in the subrange [0..N-1] The sorted sub-list has subscripts in the subrange [N..N] which is not occupied physically (hence, it does not exist, it is the empty set) For K from 0 to N-1, in increments of 1, perform Search the unordered sub-list [0..N-1-K] for the largest value and store its position P Exchange the largest element with the last element in the sub- list using positions P and N-1-K. /* The exchange adds the largest element to the beginning of the sorted sub-list, while removing it from the end of the unsorted sub-list */ 31 45 56 62 72 82 87 90 0 N-1 (N-1-K)
  • Slide 52
  • Sorting Algorithms - Selection void SelectionSort ( double List[ ], int N ) { int J, K, P ; double Temp ; for( J = 0 ; J < N-1 ; J++ ) { P = 0 ; for( K = 0 ; K < N - J ; K++ ) if( List[P] < List[K] ) P = K ; Temp = List[P] ; List[P] = List[N-1-J] ; List[N-1-J] = Temp ; } } Swapping of array elements must be done with some care and thought. Three statements are required, and a temporary storage variable must be used. Temp List[P] List[N-1-J] 62 56 1 62 2 3 56 62
  • Slide 53
  • Sorting Algorithms - Selection void SelectionSort ( double List[ ], int N ) { int J, K, P ; double Temp ; for( J = 0 ; J < N-1 ; J++ ) { P = 0 ; for( K = 0 ; K < N - J ; K++ ) if( List[P] < List[K] ) P = K ; Temp = List[P] ; List[P] = List[N-1-J] ; List[N-1-J] = Temp ; } } /* Define a dswap function */ void dswap ( double * A, double * B ) { double T ; T = *A ; *A = *B ; *B = T ; return ; } dswap ( &List[P], &List[N-1-J] ) ;
  • Slide 54
  • Sorting Algorithms - Selection void SelectionSort ( double List[ ], int N ) { int J, K, P ; double Temp ; for( J = 0 ; J < N-1 ; J++ ) { P = 0 ; for( K = 0 ; K < N - J ; K++ ) if( List[P] < List[K] ) P = K ; Temp = List[P] ; List[P] = List[N-1-J] ; List[N-1-J] = Temp ; } How many operations must be performed? Sum from J = 0 to N-2 Sum from K = 0 to N-1-J Core loop logic (CoreOps) Gauss dealt with this problem and developed several formulae which bear his name. In this case the answer is: N ( N 1 ) CoreOps
  • Slide 55
  • Sorting Algorithms - Selection The maximum number of operations required to sort a list of N elements in ascending order is N ( N 1 ) CoreOps The CoreOps consist of several fetches, one comparison and either 1 or 2 assignments (stores) This is, essentially, a constant value Thus, the time complexity of the Selection Sort algorithm is O( N 2 )
  • Slide 56
  • Sorting Algorithms There are many other sorting algorithms BubbleSort InsertionSort QuickSort MergeSort Some of these are iterative, while others are recursive. A number of sorting algorithms exhibit time complexities of O( N 2 ), but some achieve better efficiencies (eg. O( N log N ) ) under certain circumstances. Additional algorithms will be discussed later in 60-141 and other computer science courses
  • Slide 57
  • Bubble Sort void BubbleSort ( double List[ ], int N ) { int J, K ; for( J = 0 ; J < N-1 ; J++ ) for( K=0; K
  • Recursive Binary Search Binary Search can be expressed very elegantly using recursion int BinSearch ( float VS, float V[ ], int Lo, int Hi ) { int Mid ; if( Lo > Hi ) return -1 ; Mid = ( Lo + Hi ) / 2 ; if( VS == V[Mid] ) return Mid ; if( VS < V[Mid] ) return BinSearch( VS, V, Lo, Mid-1 ); else return BinSearch( VS, V, Mid+1, Hi ); } Example usage for calling: P = BinSearch( VS, V, 0, N-1 ) ; if( P == -1 ) printf( Value %lf not found, VS ) ; else printf( Value %lf found at position %d\n, VS, P ) ;
  • Slide 60
  • Recursive Functions Many algorithms are beautifully and elegantly expressed using recursion Programming recursion requires some experience to perfect, however it is considered a more natural way of thinking to most humans It is true, in general, that any iterative algorithm can be expressed as a recursive algorithm and vice versa. In practice, it is not so obvious ! Students will be tested on recursion.
  • Slide 61
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 62
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 63
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 64
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 65
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 66
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 67
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 68
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 69
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 70
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 71
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 72
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 73
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 74
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 75
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 76
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 77
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 78
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 79
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 80
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 81
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 82
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 83
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 84
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 85
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 86
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 87
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 88
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 89
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 90
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 91
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC
  • Slide 92
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. !! DONE !! ABC
  • Slide 93
  • Towers of Hanoi Base Case 1 :: Move plate from A to B ABC
  • Slide 94
  • Towers of Hanoi Base Case 1 :: Move plate from A to B Hanoi ( A, B, C, 1 ) ; /* Move from A to B, C not used */ ABC
  • Slide 95
  • Towers of Hanoi Base Case 2 :: ABC
  • Slide 96
  • Towers of Hanoi Base Case 2 :: Move top plate from A to C ABC
  • Slide 97
  • Towers of Hanoi Base Case 2 :: Move top plate from A to C Move bottom plate from A to B ABC
  • Slide 98
  • Towers of Hanoi Base Case 2 :: Move top plate from A to C Move bottom plate from A to B Move top plate from C to B Hanoi ( A, B, C, 2 ) ; /* Move from A to B, but use C */ ABC An intriguing idea starts to emerge.... Hanoi ( A, B, C, 2 ) was accomplished by First applying : Hanoi ( A, C, B, 1 ) Then applying : Hanoi ( A, B, C, 1 ) And, finally : Hanoi ( C, B, A, 1 )
  • Slide 99
  • Towers of Hanoi Base Case 3 :: Move top plate from A to B Move middle plate from A to C Move top plate from B to C Move bottom plate from A to B Move top plate from C to A Move middle plate from C to B Move top plate from A to B ABC
  • Slide 100
  • Towers of Hanoi Base Case 3 :: Move top plate from A to B Move middle plate from A to C Move top plate from B to C Move bottom plate from A to B Move top plate from C to A Move middle plate from C to B Move top plate from A to B ABC
  • Slide 101
  • Towers of Hanoi Base Case 3 :: Move top plate from A to B Move middle plate from A to C Move top plate from B to C Move bottom plate from A to B Move top plate from C to A Move middle plate from C to B Move top plate from A to B ABC This seems to be getting complicated, until we realize that Hanoi ( A, B, C, 3 ) can be expressed as : Hanoi ( A, C, B, 2 ) ; Hanoi ( &A[2], &B[2], C, 1 ) ; Hanoi ( C, B, A, 2 ) ;
  • Slide 102
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. ABC In general, applying mathematical induction, we find that Hanoi ( A, B, C, N ) can be expressed as : void Hanoi ( int A[ ], int B[ ], int C[ ], int N ) { if( N == 1 ) { B[0] = A[0] ; return ; } if( N == 2 ) { C[0] = A[0] ; A[0] = B[0] ; C[0] = B[0] ; return ; } Hanoi ( A, C, B, N-1 ) ; Hanoi ( &A[N-1], &B[N-1], C, 1 ) ; Hanoi ( C, B, A, N-1 ) ; return ; }
  • Slide 103
  • Towers of Hanoi Problem: Move all plates from A to either B or C, such that at all times smaller plates are on top of larger plates. !! DONE !! ABC Most people are able to grasp the sequence of movements to solve the Towers of Hanoi problem. The solution is recursive, built up from handling base cases of N=1, 2 and 3 plates. Once the pattern is understood, it is then reapplied to arbitrary N. Programming an iterative algorithm is much harder, however. ( Try it but in your spare time :)
  • Slide 104
  • Multi-Dimensional Arrays Consider the case of student marks (0.0 to 10.0) for several assignments, all stored in a 2- dimensional array of float values #define MAX_STUDS 120 #define NUM_ASSIGNS 10 float Mark [ MAX_STUDS ] [ NUM_ASSIGNS ] ; Assume data is in a file called InData.dat. StudentNumber AssignNumber
  • Slide 105
  • Multi-Dimensional Arrays We assume that the input file InData.dat has been prepared as follows: The file may be empty, in which case the end-of-file indicator can be checked using EOF A non-empty file contains (at the least) One line containing two integer values greater or equal to zero These correspond to the number of students and number of assignments, respectively The rest of the file contains A line containing an integer, the Student Number, followed by A line containing the marks as floating point values. The number of marks corresponds to the number of assignments specified. The file terminates when the end-of-file indicator arises and is checked using EOF. Marks must be inserted according to the Student Number value (in the range from 0 to MAX_STUDS-1). StudentNumber AssignNumber
  • Slide 106
  • Multi-Dimensional Arrays /* Input from InData.dat using input redirection cmdprompt:>a.out < InData.dat */ #define MAX_STUDS 120 #define NUM_ASSIGNS 10 float Mark [ MAX_STUDS ] [ NUM_ASSIGNS ] ; int NumberStudents, NumberAssignments, StudNum ; int S, A ; /* Utility integers */ /* Test input file for data */ if( (A=scanf( %d%d, &NumberStudents, &NumberAssignments )) == EOF ) return 0 ; /* Data exists, so input data until EOF is encountered */ for( S=0 ; S < NumberStudents ; S++ ) { if ( (A=scanf( %d, &StudNum )) == EOF ) break; /* A record exists so input assignment marks */ for( A=0 ; A < NumberAssignments ; A++ ) scanf( %f, &Mark[ StudNum ][A] ) ; }
  • Slide 107
  • Multi-Dimensional Arrays N-D Arrays as function arguments Unlike 1-D arrays, all array maximum dimensions must be declared explicitly (except for the leftmost dimension) Example InputMarks( NS, NA, Mark ) Prototype void InputMarks( int, int, float [][ NUM_ASSIGNS ] ) ; Function Definition void InputMarks( int NS, int NA, float M[][ NUM_ASSIGNS ] ) { /* variable defns, logic */ return ; }
  • Slide 108
  • Multi-Dimensional Arrays Memory allocation of 2D arrays is done (typically) using Row Major Ordering. The compiler must know, in advance, what size of allocation to provide for each row The actual number of rows is not important 123 456 789 101112 1 2 3 4 5 6 7 8 9 10 11 12
  • Slide 109
  • Multi-Dimensional Arrays Memory allocation of 2D arrays is done (typically) using Row Major Ordering. The compiler must know, in advance, what size of allocation to provide for each row The actual number of rows is not important The compiler replaces subscript references by Base address pointer plus relative offset The Base address is just the address of the first element in the 2D array, or &A[0][0] The relative offset is given by Rowsub * ( #Columns * sizeof elementtype) + Colsub * sizeof elementtype To compute this expression requires the #Columns void InputMarks( int, int, float [] [NUM_ASSIGNS] ) ; Rowsub * ( #Columns * sizeof elementtype) + Colsub * sizeof elementtype Higher dimensional arrays must specify all lower dimensions maximum values, leaving only the highest dimension unspecified. Example prototype statement for a 3D array: int Func( int Array [ ] [ MAX_ROW ] [ MAX_COL ], int Page, int Row, int Col ) ; The allocation is understood in terms of Page Major Ordering which requires that the compiler know MAX_ROW and MAX_COL in advance.
  • Slide 110
  • Multi-Dimensional Arrays Working with 2-D arrays necessitates thought and care about the operations to be performed on them and how they are defined and referenced Matrix Transpose - Transpose( A, AT, NR, NC ) Interchange rows and columns Prototype: void Transpose( float [ ] [MC], float [ ] [MR], int, int ) ; The result array must be defined to be of suitable size If we define: float A [MR] [MC]; then we must define: float AT [MC] [MR]; Key statement for( r=0; r A[ r2 ][ 0 ] ) for( c=0 ; c