arrays data structures - structured data are data organized to show the relationship among the...

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

Post on 21-Dec-2015

213 views

Category:

Documents


0 download

TRANSCRIPT

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

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.

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

Arrays

For example, to declare a 9-element array named first of type char you would use this statement.

char first [ 9 ];Type of elementscontained in thearray (i.e. int,

char, double, etc.)array name

array size - numberof 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]

127601276112762127631276412765127661276712768

12759

•••••

Notice indexing starts with 0

Notice that the last subscript is one less the size

of the array

memory

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

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 */

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

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 bycommas

2 3 5 7 9

Size not specified Number of values set the size of the

array2 4 6 8 10

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

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 };

2 4 0 0 0

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 ] );

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

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.

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

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 <stdio.h>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;}

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

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 <stdio.h>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 );}

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

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.

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

43 22 3617 16

[0] [1] [2] [3] [4]Pass 1:

Operation

Find smallest of all five elements and swap it with numbers[ 0 ]

numbers [ 5 ]

16 22 3617 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 3622 43

[0] [1] [2] [3] [4]Pass 3: Find smallest of the last three elements and swap it with numbers[ 2 ] (already smallest)

16 17 3622 43

[0] [1] [2] [3] [4]Pass 4: Find smallest of the last two elements and swap it with numbers[ 3 ]

16 17 4322 36

[0] [1] [2] [3] [4]Sortedarray:

Done! (last element sorted)

=> sorted element

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

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;}

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

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.

43 22 3617 16

[0] [1] [2] [3] [4]Pass 1:

Operation

Compare [ 3 ] to [ 4 ] and swap if [ 4 ] is less than [ 3 ]

numbers [ 5 ]

43 22 3617 16

[0] [1] [2] [3] [4]Step 2: Compare [ 2 ] to [ 3 ] and swap if [ 3 ] is less than [ 2 ]

43 22 3616 17

[0] [1] [2] [3] [4]Step 3: Compare [ 1 ] to [ 2 ] and swap if [ 2 ] is less than [ 1 ]

43 16 3622 17

[0] [1] [2] [3] [4]Step 4: Compare [ 0 ] to [ 1 ] and swap if [ 1 ] is less than [ 0 ]

16 43 3622 17

[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 3622 17

[0] [1] [2] [3] [4]Step 2: Compare [ 2 ] to [ 3 ] and swap if [ 3 ] is less than [ 2 ]

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

=> sorted element

16 43 3617 22

[0] [1] [2] [3] [4]Pass 2(continued):

Operation

Compare [ 1 ] to [ 2 ] and swap if [ 2 ] is less than [ 1 ]

numbers [ 5 ]

16 17 3643 22

[0] [1] [2] [3] [4]Step 1: Compare [ 3 ] to [ 4 ] and swap if [ 4 ] is less than [ 3 ]

16 17 3643 22

[0] [1] [2] [3] [4]Step 3: Compare [ 2 ] to [ 3 ] and swap if [ 3 ] is less than [ 2 ]

16 17 3622 43

[0] [1] [2] [3] [4]Step 4: Compare [ 3 ] to [ 4 ] and swap if [ 4 ] is less than [ 3 ]

16 17 4322 36

[0] [1] [2] [3] [4]Done!

Step 3:

SortedArray:

Arrays

Pass 3:

Pass 4:

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

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;}

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

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.

43 22 3617 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 ]

22 43 3617 16

[0] [1] [2] [3] [4]Pass 2:

Insertion Sort:

17 22 3643 16

[0] [1] [2] [3] [4]Pass 3:

16 17 3622 43

[0] [1] [2] [3] [4]Pass 4:

16 17 4322 36

[0] [1] [2] [3] [4]Sortedarray:

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]

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

ArraysInsertion 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;

}

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

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.

43 22 3617 16

[0] [1] [2] [3] [4]

Operation

Compare [ 0 ] to key, stop if they match

numbers [ 5 ]

43 22 3617 16

[0] [1] [2] [3] [4]Step 2:

Sequential Search:

43 22 3617 16

[0] [1] [2] [3] [4]Step 3:

43 22 3617 16

[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!

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

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] );

}

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

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 0set last to 6compute mid = 3key > mid

numbers [ 5 ]

Step 2:

Sequential Search:

Step 1:

Search key = 24

Set first to 4 compute mid = 5key = mid Done!

12 15 3617 18

[0] [1] [2] [3] [5]

first lastmid

20

[4]

24

[6]

12 15 3617 18

[0] [1] [2] [3] [5]

first lastmid

20

[4]

24

[6]

12 15 3617 18

[0] [1] [2] [3] [5]

20

[4]

24

[6]Key found:

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

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 0 Column 1 Column 2

Array element value

Array element reference

Array element reference:scores [ i ] [ j ]

Array name

Row subscript

Column subscript

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

Arrays

Two-Dimensional Arrays initialization:

int score [ 4 ] [ 3 ] = {

{ 90, 82, 76 },{ 92, 81, 99 },{ 89, 95, 95 },{ 98, 69, 93 }

}

Note commasbetween 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 dimensioncan be omitted but all others must be

specified.