290 likes | 350 Views
Arrays. Why we need data structure ? Simple data types use a single memory cell to store a variable. Sometimes (for example scores of a class) it is more efficient to group data items together in main memory.
E N D
Arrays • Why we need data structure? • Simple data types use a single memory cell to store a variable. • Sometimes (for example scores of a class) it is more efficient to group data items together in main memory. • C++ allows to group related data items together into a single composite data structure. • Array is one such data structure. • Array => A collection of data items of the same type.
Array x 2 4 7 9 1 x[4] x[0] x[1] x[2] x[3] Subscripted variable => x[0] Read as x sub zero. Declaring & Referencing Arrays • Array => collection of two or more adjacent memory cells (array elements). • To set up an array in memory, we must declare • - the name of the array and • - the number of cells associated with it. • int x[5]; Instructs the compiler to associate 5 memory cells with the name x array subscript
Array Subscripts • Array subscript=> integer enclosed in brackets • => its value in the range: 0 - (array_size - 1). • Use of array subscript => to differentiate between the individual array elements. • => to specify which array element is to be manipulated. • We can use any expression of type int as an array subscript. • typedef enum • { monday, tuesday, wednesday, thursday,friday} • class_days_t; • int score[NUM_CLASS_DAYS]; Five class days
5 7 4 9 score [monday] 4 score [tuesday] score [wednesday] score [thursday] score [friday] Array subscript • typedef enum • { monday, tuesday, wednesday, thursday,friday} • class_days_t; • int score[NUM_CLASS_DAYS]; We can use enumeration constants monday through friday as array subscripts since the they are represented by the integers 0 through 4. array subscript array value
Array Initialization • If there are fewer initializers than elements in the array, the remaining elements are automatically initialized to zero. • Example: int n[10] = {0}; • Note: Arrays are not automatically initialized to zero. • The programmer must at least initialize the first element to zero. Then the remaining elements will be automatically initialized to zero. • Initialize an array with declaration: • int odd_num[5] = {1, 3, 5, 7, 9}; • int odd_num[] = {1, 3, 5, 7, 9}; • Syntax error: int n[5] = {3, 5, 7, 9, 11, 12} 5 array elements 6 initializers
0 1 8 27 64 Sequential Access • We can access the elements of an array in sequence by using an indexed for loop. • - Loop control variable runs from zero to one less than the array size. • - Loop counter is used as an array index(subscript) to access each element in turn. • Example: • int cube[5], i; • The for loop • for (i = 0; i < 5; ++i) • cube[i] = i * i * i; initializes this array :
Compute the Sum and the Sum of the Squares of all Data • sum = x[0] +x[1] + x[2] + x[3] + x[4] + x[5] = x[i]; • sum_sqr = x[0] 2 +x[1] 2+ x[2] 2+ x[3] 2+ x[4] 2+ x[5]2 = x[i]2; • int i, sum = 0; • int sum_sqr = 0; • for (i = 0; i < MAX_ITEM; ++i) • { • sum += x[i]; or sum = sum + x[i]; • sum_sqr += x[i] * x[i]; or sum_sqr = sum_sqr + x[i] * x[i]; • }
2 4 7 9 1 Array Elements as Function Arguments Array x #include <iostream.h> int main() { int x[5] = {2, 4, 7, 9, 1}; cout << “The first element is: “ << x[0] << endl; } • Another function: cin >> x[2]; Result: The first element is: 2 The scanned value will be stored in the array element x[2].
Array as Function Arguments • We can also pass arrays as function arguments. • An array name with no subscript appears in the argument list of the function. • The address of the initial array element is stored in the function’s corresponding formal parameter. • void fill_array ( int list[], // list of n integers • int n, // number of list elements • int in_value) // initial value • { • int i; • for ( i = 0; i < n; ++i) • list[i] = in_value; • }
1 1 1 1 1 Array as Function Arguments Function fill_array Data Area Calling function Data Area • Data Areas Before Return from fill_array(x, 5, 1). x list [0] [1] n [2] [3] in_value [4] i
Array as Function Arguments • The function manipulates the original array, not its own personal copy. • So an assignment to one of the array elements by a statement in the function changes the contents of the original array. • list[i] = in_value; • ANSI C++ provides a qualifier const to notify the C++ compiler that • - the array is only an input to the function and • - the function should not be allowed to modify array elements. • - the elements of the array become constant in the function body. • - any attempt to modify an element of the array in the function body results in a compile time error. • Example: • int get_max(const int list[], // input- list of n integers • int n) // input- number of list elements
Returning an Array Result • In C++, it is not legal for a function’s return type to be an array. • It requires the use of an output parameter to send the result array back to the calling function. • Example: • void add_arrays(const int arg1[], // input • const int arg2[], // input • int argsum[], // output • int n) // input • { • for (i = 0; i < n; ++i) • argsum[i] = arg1[i] + arg2[i]; // adds corresponding elements // of arg1 and arg2 • }
Why we apply Static to a Local Array Declaration? • We can apply static to a local array declaration so that • - the array is not created and initialized each time the function is called, and • - the array is not destroyed each time the function is exited in the program. • - this reduces program execution time particularly for programs with frequently called functions that contain large arrays.
C + 2 Stacks • A stack is a data structure in which only the top element can be accessed. • Example: • A stack of plates in cafeteria. • A customer always takes the top plate. • When a plate is removed, the plate beneath it moves to the top. Stack of three characters Top of the stack Push => storing an item in a stack pop=> removing an item from a stack
Function push • void push(char stack[], // input/output - the stack • char item, // input - data being pushed onto the stack • int *top, // input/output - pointer to top of stack • int max_size) // input - maximum size of stack • { • if (*top < max_size - 1) • { • ++(*top); • stack[*top] = item; • } • }
Function Pop • char pop(char stack[], // input/output - the stack • int *top) // input/output - pointer to top of stack • { • char item; // value popped off the stack • if (*top >= 0) • { • item = stack[*top]; • --(*top); • } • else • item = STACK_EMPTY; • return (item); • }
C + 2 How to create a stack using Array? • char s[STACK_SIZE]; • int s_top = -1; • The statements : • push(s, ‘2’, &s_top, STACK_SIZE); • push(s, ‘+’, &s_top, STACK_SIZE); • push(s, ‘C’, &s_top, STACK_SIZE); • create the stack : • pop(s, &s_top); • create the stack: + 2
Searching an Array • We search an array to determine the location of a particular value (target). • Example: We need to search an array to determine the score of a particular student. • Two popular techniques: linear search and binary search • Linear search: • To search an array, first we need to know the array element value we are seeking ( target). • Then we have to examine each array element whether it matches the target by using a loop. • When the target is found, the search loop should be exited.
Algorithm for Searching (Linear) an Array • Assume the target has not been found. • Start with the initial array element. • Repeat while the target is not found and there are more array elements • 4 if the current element matches the target • 5 Set a flag to indicate that the target has been found. • else • 6 Advance to the next array element. • if the target was found • 8 Return the target index as the search result. • else • 9 Return -1 as the search result.
Function for Linear Searching of an Array • constant NOT_FOUND = -1; • int search(const int arr[], int target, int n) • { • int i = 0, found = 0, where; • while (!found && i < n) // Compare each element to target • { • if (arr[i] == target) • found = 1; • else • ++i; • } • if (found) // Returns index of element matching target or • where = i; // NOT_FOUND • else • where = NOT_FOUND; • return (where); • }
Binary Search • The binary search algorithm eliminates half of the elements in the array being searched after each comparison. • The algorithm locates the middle element of the array and compares it to the target. • If they are equal, the target is found and the array subscript of that element is returned. • If they are not equal, the problem is reduced to searching one half of the array. • If the target is less than the middle element of the array, the first half of the array is searched. • Otherwise the second half of the array is searched. • If the target is not found in the specified subarray, the algorithm is repeated on one quarter of the original array. • The search continues until the target is equal to the middle element of a subarray, or until the subarray contains one element that is not equal to the target.
Function for Binary Searching of an Array • int binarySearch( int list[], int target, int low, int high ) • { • int middle; • while ( low <= high ) • { • middle = ( low + high ) / 2; • if ( target == list[middle] ) • return middle; • else if ( target < list[middle] ) • high = middle - 1; • else • low = middle + 1; • } • return -1; • }
Comparison of Linear and Binary Search • Linear search compares each element of the array with the target. On average , therefore the program will compare the target with half of the elements of the array. • Linear search works well for small arrays or for unsorted arrays. However, for large arrays linear searching is inefficient. • For a large and sorted array, the high speed binary search technique can be used. • In a worst case scenario, searching in an array of 1024 elements will take only 10 comparisons using a binary search. An array of one billion elements takes a maximum of 30 comparisons to find the target. • 2 10 = 1024 1000 • 2 30 = 1024 * 1024 * 1024 1000000000
Sorting an Array • Many programs execute more efficiently if the data are sorted before processing. • Example: Your grade reports can be sorted according to your student ID numbers. A bank sorts all checks by account number. • Selection sort is a fairly simple but not very efficient sorting algorithm. • To perform a selection sort of an array of n elements, first you have to locate the smallest element in the array. • Then switch the smallest element with the element at subscript 0. • Then locate the smallest element in the subarray with subscripts 1 through n -1. • Then switch the the smallest (second smallest) element in the second position. • And so on.
Algorithm for Selection Sort • for each value of fill from 0 to n -2 • 2 Find index_of_min, the index of the smallest element in the unsorted subarray list[fill] through list[n -1]. • 3 if fill is not the position of the smallest element (index_min) • 4 Exchange the smallest element with the one at position fill.
Function select_sort • int get_min_range (int list[], int first, int last); • void select_sort (int list[], int n) • { • int fill, temp, index_of_min; • for (fill = 0; fill < n -1; ++fill) • { • index_of_min = get_min_range(list, fill, n -1); • if (fill != index_of_min) • { • temp = list[index_of_min]; • list[list_of_min] = list[fill]; • list[fill] = temp; • } • } • }
74 45 83 16 16 45 83 74 16 45 83 74 16 45 74 83 Selection Sort Fill is 0. Find the smallest element in subarray list[0] through list[3] and swap it with list[0] • Trace of selection sort Fill is 1. Find the smallest element in subarray list[1] through list[3] - no exchange needed. Fill is 2. Find the smallest element in subarray list[2] through list[3] and swap it with list[2].
O O X X X O O X X Multidimensional Array • Multidimensional array => array with two or more dimensions. • We use two dimensional arrays to represent tables of data, matrices, and other two-dimensional objects. • A two dimensional object is a tic-tac-toe board. • The array declaration: char tictactoe[3][3]; or char tictactoe[][3]; • The array initialization: • char tictactoe [3][3] = {{‘ ‘, ‘ ‘, ‘ ‘}, {‘ ‘, ‘ ‘, ‘ ‘}, {‘ ‘, ‘ ‘, ‘ ‘}}; Column tictactoe[0][2] 0 1 2 0 1 Row 2
Array with Several Dimensions Used to store the enrollment data for a school. course campus year • int enroll [MAXCRS][5][4] Problem: College offers 100 (MAXCRS) courses at five different campuses. We numbered the freshman year 0, the sophomore year 1, and so on. Find the number of juniors in all classes at all campuses. Students will be counted once for each course in which they are enrolled. int i, j, num_junior; // number of juniors num_junior = 0; for ( i = 0; i < MAXCRS; ++i) for ( j = 0; j < 5; ++j) num_junior += enroll[i][j][2];