Presentation is loading. Please wait.

Presentation is loading. Please wait.

Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.

Similar presentations


Presentation on theme: "Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism."— Presentation transcript:

1 Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism to organize the data. One common organizing technique, arrays, allows us to process the data as a group and as individuals elements. An array is a fixed-size, sequenced collection of elements of the same data type. An array has a name and has one or more elements which are referenced through an index (subscript ). Declaring an array - The general form for declaring a single- dimensioned array is: type name [size] ; Like other variables, arrays must be explicitly declared so that the compiler may allocate space for them in memory. Here, type declares the base type of the array which is the type of each element in the array. name is the name of the array which must follow the C naming rules. size defines how many elements the array will hold. The size of the array must have a value at compilation time and therefore must be a constant.

2 Arrays For example, to declare a 9-element array named first of type char you would use this statement. char first [ 9 ]; Type of elements contained in the array (i.e. int, char, double, etc.) array name array size - number of elements in the array. Must be a constant of type integer!! This declaration creates an array with 9 elements of type char. This tells the compiler to allocate 9 adjacent memory cells for type char values indexed from 0 to 8. The amount of storage required to hold an array is directly related to its type and size. For a single-dimension array, the total size in bytes is computed as shown here: total bytes = sizeof (type) * size of array first[0] first[1] first[2] first[3] first[4] first[5] first[6] first[7] first[8] 12760 12761 12762 12763 12764 12765 12766 12767 12768 12759 Notice indexing starts with 0 Notice that the last subscript is one less the size of the array memory

3 Arrays Accessing Elements in Arrays - C uses an index to access individual elements in an array. The index must be an integral value or an expression that evaluates to an integral value. The simplest form for accessing an element is a numeric constant. Typically, however, the index is a variable or an expression. To access the fifth element in the array named first above use the expression: first [ 4 ] Notice that since the first subscript value is zero the fifth element would be 4 ( 0,1,2,3,4 ). The above expression results in the value stored in the content of the fifth element of array named first. The array’s name is a symbolic reference for the address to the first byte of the array. Whenever we use the array’s name, therefore, we are actually referring to the first byte of the array. The index represents an offset from the beginning of the array to the element being referred to. char *arrayP; arrayP = first; /* assigns the address of the first element of array named first to pointer arrayP */

4 Arrays Storing values in Arrays - If we want to store values in the array, we must either initialize the elements, read values from the keyboard, or assign values to each individual element. Initialization - all elements in an array can be done at the time of declaration, just like simple variables int numbers [ 5 ] = { 2, 3, 5, 7, 9 }; When the array is completely initialized, it is not necessary to specify the size of the array. int numbers [ ] = { 2, 4, 6, 8, 10 }; Notice the braces Values separated by commas Size not specified Number of values set the size of the array

5 Arrays If the number of values provided is less than the number of elements in the array, the unassigned elements are filled with zeros. int numbers [ 5 ] = { 2, 4 }; Individual elements can be assigned values using the assignment operator. A simple assignment statement for numbers would be: numbers [ 2 ] = 45 ; on the other hand you cannot assign one array to another array, even if they match fully in type and size. Another way to fill the array is to read the values from the keyboard or a file. This can be done using a loop: for ( i = 0; i < 5; i++ ) scanf ( “%d”, &numbers[ i ] );

6 Arrays C has no bounds checking on arrays. You could overwrite either end of an array and write into some other variable's data or even into the program’s code. As the programmer, it is your job to provide bounds checking where needed. For example, this code will compile without error, but is incorrect because the for loop will cause the array count to be overrun: int count [10], i; /* this causes count to be overrun */ for(i = 0; i < 100; i++ ) count [ i ] = i; So you want to plan your array logic carefully and fully test it.

7 Arrays Arrays and functions - To process arrays in a large program, you have to be able to pass them to functions. You can do this in two ways; pass individual elements or pass the whole array. Individual elements can be passed to a function like any ordinary variable. Of course it will be passed as a value parameter, which means that the function cannot change the value of the element. #include int main (void) { void print_square (int ); int i ; int base[ 5 ] = { 3, 7, 2, 4, 5 }; for ( i = 0; i < 5; i++) print_square ( base [ i ] ); return 0; } void print_square( int x ) { printf(“%d”, x * x ); return; }

8 Arrays If we want the function to operate on the whole array, we must pass the whole array. To do this C passes the address of the array. You must follow two rules to pass the whole array to a function: 1) The function must be called by passing only the name of the array(the address of the first element). 2) In the function definition, the formal parameter must be an array type: the size of the array does not need to be specified. #include int main (void) { double average (int [ ] ); double ave ; int base[ 5 ] = { 3, 7, 2, 4, 5 }; ave = average ( base );... return 0; } double average( int x [ ] ) { int i, sum = 0; for ( i = 0; i < 5; i ++ ) sum += x [ i ]; return ( sum / 5.0 ); }

9 Arrays Sorting Arrays - One of the most common applications in computer science is sorting, which is the process through which data are arranged according to their values. Sorting is the process of transforming a list into an equivalent list, in which the elements are arranged in ascending or descending order. Sorting lists are especially important in list searching because they facilitate search operations. Because of the importance of sorting in practical applications, many sorting techniques have been developed. Selection Sort - A list (array) is divided into sorted and unsorted. We first find the smallest element in the unsorted part of the list and then swap this element with the first element in the unsorted list. By doing this, the sorted list increases in size and the unsorted list decreases in size.

10 432236 17 16 [0][1][2][3][4] Pass 1: Operation Find smallest of all five elements and swap it with numbers[ 0 ] numbers [ 5 ] 162236 17 43 [0][1][2][3][4] Pass 2: Find smallest of the last four elements and swap it with numbers[ 1 ] Arrays Selection Sort: 16 17 362243 [0][1][2][3][4] Pass 3: Find smallest of the last three elements and swap it with numbers[ 2 ] (already smallest) 16 17 362243 [0][1][2][3][4] Pass 4: Find smallest of the last two elements and swap it with numbers[ 3 ] 16 17 432236 [0][1][2][3][4] Sorted array: Done! (last element sorted) => sorted element

11 Arrays Selection Sort Algorithm void selectionSort (int list [ ], int last ) { void exchangeSmallest (int list[ ], int first, int last); int current; for ( current = 0 ; current < last ; current++) exchangeSmallest ( list, current, last); return; } void exchangeSmallest (int list [ ], int current, int last ) { int walker, smallest, tempData; smallest = current; for ( walker = current +1 ; walker <= last ; walker++) if (list[walker] < list[smallest] ) smallest = walker ; tempData = list[current]; list[current] = list[smallest]; list[smallest] = tempData; return; }

12 Arrays Bubble Sort - A list (array) is divided into sorted and unsorted. The smallest element is bubbled from the unsorted sublist and moved to the sorted sublist. By doing this, the sorted list increases in size and the unsorted list decreases in size. 432236 17 16 [0][1][2][3][4] Pass 1: Operation Compare [ 3 ] to [ 4 ] and swap if [ 4 ] is less than [ 3 ] numbers [ 5 ] 432236 17 16 [0][1][2][3][4] Step 2: Compare [ 2 ] to [ 3 ] and swap if [ 3 ] is less than [ 2 ] 43 22 361617 [0][1][2][3][4] Step 3: Compare [ 1 ] to [ 2 ] and swap if [ 2 ] is less than [ 1 ] 43 16 362217 [0][1][2][3][4] Step 4: Compare [ 0 ] to [ 1 ] and swap if [ 1 ] is less than [ 0 ] 16 43 362217 [0][1][2][3][4] Step 1: Compare [ 3 ] to [ 4 ] and swap if [ 4 ] is less than [ 3 ] Step 1: Pass 2: 16 43 362217 [0][1][2][3][4] Step 2: Compare [ 2 ] to [ 3 ] and swap if [ 3 ] is less than [ 2 ]

13 => sorted element 164336 17 22 [0][1][2][3][4] Pass 2 (continued): Operation Compare [ 1 ] to [ 2 ] and swap if [ 2 ] is less than [ 1 ] numbers [ 5 ] 161736 43 22 [0][1][2][3][4] Step 1: Compare [ 3 ] to [ 4 ] and swap if [ 4 ] is less than [ 3 ] 16 17 364322 [0][1][2][3][4] Step 3: Compare [ 2 ] to [ 3 ] and swap if [ 3 ] is less than [ 2 ] 16 17 362243 [0][1][2][3][4] Step 4: Compare [ 3 ] to [ 4 ] and swap if [ 4 ] is less than [ 3 ] 16 17 432236 [0][1][2][3][4] Done! Step 3: Sorted Array: Arrays Pass 3: Pass 4:

14 Arrays Bubble Sort Algorithm void bubbleSort (int list [ ], int last ) { void bubbleUp (int list[ ], int first, int last); int current; for ( current = 0 ; current < last ; current++) bubbleUp ( list, current, last); return; } void bubbleUp (int list [ ], int current, int last ) { int walker, tempData; for ( walker = last ; walker > current ; walker--) if (list[walker] < list[walker - 1] ) { tempData = list[walker] ; list[walker] = list[walker - 1]; list[walker - 1] = tempData; } return; }

15 Arrays Insertion Sort - A list (array) is divided into sorted and unsorted. In each pass, the first element of the unsorted sublist is picked up and transferred into the sorted sublist by inserting it at the appropriate place. By doing this, the sorted list increases in size and the unsorted list decreases in size. 432236 17 16 [0][1][2][3][4] Pass 1: Operation Set temp to the value of [1], find the insertion point ( [0] ), shift elements to right of insertion point and copy temp to [0] numbers [ 5 ] 224336 17 16 [0][1][2][3][4] Pass 2: Insertion Sort: 17 22 364316 [0][1][2][3][4] Pass 3: 16 17 362243 [0][1][2][3][4] Pass 4: 16 17 432236 [0][1][2][3][4] Sorted array: Done! => sorted element Set temp to the value of [2], find the insertion point ( [0] ), shift elements to right of insertion point and copy temp to [0] Set temp to the value of [3], find the insertion point ( [0] ), shift elements to right of insertion point and copy temp to [0] Set temp to the value of [4], find the insertion point ( [3] ), shift elements to right of insertion point and copy temp to [3]

16 Arrays Insertion Sort Algorithm void insertSort (int list [ ], int last ) { void insertOne (int list[ ], int first); int current; for ( current = 1 ; current <= last ; current++) insertOne ( list, current); return; } void insertOne (int list [ ], int current) { int walker, located, temp; located = 0; temp = list[current]; for ( walker = current - 1; walker >= 0 && !located; ) if (temp < list[walker] ) { list[walker + 1] = list[walker]; walker-- ; } else located = 1 ; list [ walker + 1 ] = temp; return; }

17 Arrays Searching Arrays - Another common operation on arrays is the search operation. We search a list stored in an array to determine whether it contains an element that matches a given search key value. Sequential Search - The sequential search can be used to locate an item in any array. Generally you will use this technique only for small lists or lists that are not searched often. We start searching for the target value from the beginning of the list, and we continue until we find the target or we have reached the end of the list. 432236 17 16 [0][1][2][3][4] Operation Compare [ 0 ] to key, stop if they match numbers [ 5 ] 432236 17 16 [0][1][2][3][4] Step 2: Sequential Search: 43 22 361716 [0][1][2][3][4] Step 3: 43 22 361716 [0][1][2][3][4] Key found: Step 1: Search key = 17 Compare [ 1 ] to key, stop if they match Compare [ 2 ] to key, stop if they match Done!

18 Arrays Sequential Search int seqSearch (int list [ ], int last, int target, int *locn ) { int looker; looker = 0; while ( looker < last && target != list[looker] ) looker++ *locn = looker; return ( target == list[looker] ); }

19 Arrays Binary Search - The binary search is a more efficient but requires the list to be sorted. The binary search starts by testing the data in the element at the middle of the array. This determines if the target is in the first half or the second half of the the list. If it is the first half we do not need to check the second half anymore. If it is the second half, we don’t need to test the first half any more. The process is repeated until we find the target or satisfy ourselves that it is not in the list. Operation Set first to 0 set last to 6 compute mid = 3 key > mid numbers [ 5 ] Step 2: Sequential Search: Step 1: Search key = 24 Set first to 4 compute mid = 5 key = mid Done! 121536 17 18 [0][1][2][3][5] firstlastmid 20 [4] 24 [6] 121536 17 18 [0][1][2][3][5] firstlastmid 20 [4] 24 [6] 121536 17 18 [0][1][2][3][5] 20 [4] 24 [6] Key found:

20 Arrays Two-Dimensional Arrays - Just as we can have arrays of integers, floating-point values, and characters, we can also have arrays of arrays. An array of one-dimensional arrays is called a two-dimensional array; an array of two dimensional arrays is called a three-dimensional array, and so on. scores [ 0 ] [ 0 ] 95 scores [ 0 ] [ 1 ] 82 scores [ 0 ] [ 2 ] 76 scores [ 1 ] [ 0 ] 92 scores [ 1 ] [ 1 ] 81 scores [ 1 ] [ 2 ] 99 scores [ 3 ] [ 0 ] 98 scores [ 3 ] [ 1 ] 69 scores [ 3 ] [ 2 ] 93 scores [ 2 ] [ 0 ] 89 scores [ 2 ] [ 1 ] 95 scores [ 2 ] [ 2 ] 95 Array declaration : int scores [ 4 ] [ 3 ]; Row 0 Row 1 Row 2 Row 3 Column 0Column 1Column 2 Array element value Array element reference Array element reference: scores [ i ] [ j ] Array name Row subscript Column subscript

21 Arrays Two-Dimensional Arrays initialization: int score [ 4 ] [ 3 ] = { { 90, 82, 76 }, { 92, 81, 99 }, { 89, 95, 95 }, { 98, 69, 93 } } Note commas between rows int score [ ] [ 3 ] = { { 90, 82, 76 }, { 92, 81, 99 }, { 89, 95, 95 }, { 98, 69, 93 } } To fill values from the keyboard use a nested loop: for ( row = 0 ; row < 4 ; row++) for (column = 0 ; column < 3; column ++) scanf(“%d”, &scores [ row ] [ column ] ); The first dimension can be omitted but all others must be specified.


Download ppt "Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism."

Similar presentations


Ads by Google