Scott Marino MSMIS Kean University MSAS5104 Programming with Data Structures and Algorithms Week 10 Scott Marino
MSMIS Kean University Topics Arrays –Definition –Initialization –Referencing elements Sequential Search Sorting Binary Search Multidimensional Arrays Linked Lists Lab 7 / Homework
Scott Marino MSMIS Kean University Arrays There are instances where data comes to a program as a collection (group) of data values of the same type –Zip codes –State Abbreviations –Telephone area codes –Employees, Students, etc. Assigning a unique variable name to each value would be difficult to manage in a program
Scott Marino MSMIS Kean University Arrays Creating a common name to be used to refer to the collection of values and then using a special identifier to access each individual value simplifies the programming process In C++ a collection of values is called an array In addition to easier access, special operations can be written to access and update an array
Scott Marino MSMIS Kean University Arrays Each value in an array is referred to as an element Each element in the array must be of the same data type In C++ the array is given a name just like other variables Each individual element is identified by an index position that is enclosed in [ ] (square braces) The first index position in the array is at location 0 (zero)
Scott Marino MSMIS Kean University Arrays Area code 201 is at array position (offset) 0 In a program, Area_Code[1] contains the value 732 cout << Area_Code[3] << endl; –Will print Area_Codes
Scott Marino MSMIS Kean University Arrays Defining an array const int num_area_codes = 999; … int area_code[num_area_codes]; Use a constant value, num_area_codes to set the maximum number of elements in the array –Define the constant to be a global variable Defines an array named area_code that has num_area_codes (999) elements
Scott Marino MSMIS Kean University Arrays - Initial Values An array can be populated with initial values –int area_code[num_area_codes] = {201,732, 973}; Will populate array positions 0, 1, and 2 with the values and will initialize the rest of the elements to zero (based on data type) –int area_code[num_area_codes] = {0}; Will define the array, and explicitly initialize the first element to 0 and default the remaining elements to 0
Scott Marino MSMIS Kean University Arrays - Referencing Elements Individual elements can be updated –area_code[0] = 201; Individual elements can be referenced –my_area_code = area_code[0]; Can use an integer variable inside the brackets to refer to an element –array_pos = 0; cout << area_code[array_pos] << endl; –Will print element 0
Scott Marino MSMIS Kean University Arrays - Referencing Elements –for (loopctr = 0; loopctr < num_area_codes; loopctr++) { cout << “Element “ << loopctr << “ contains “ << area_code[loopctr] << endl; } Will iterate through each element, printing the value –This code takes advantage of the num_area_codes constant value to control the end of the loop
Scott Marino MSMIS Kean University Arrays and Functions long int sumarray (int area_code[]) { long int array_tot = 0; int i; for (i = 0; i < num_area_codes; i++) { array_tot = array_tot + area_code[i]; } return array_tot ; } The above function will return the sum total of all elements in the array
Scott Marino MSMIS Kean University Arrays and Functions The function will receive an array (passed by value) with the following syntax: –data-type array-name[] The data type of the array is required The number of elements in the array is omitted The array name can be a local name for the array as the data is being passed by value Large arrays are typically passed by reference for performance reasons
Scott Marino MSMIS Kean University Arrays and Functions Passing an array to a function has the following syntax: –function-name(array-name); The name of the array is passed to the function (by value) –There is no indication of the number of elements The global constant value for the number of elements would be used inside the receiving function
Scott Marino MSMIS Kean University Arrays and Functions The formal parameters of the above functions did not include the references to the number of elements To write more generic functions that could be reused much easier, the function should receive 2 parameters, the array itself, and the number of elements in the array –Sort, search, and other array functions could be put into a header file and used in many programs
Scott Marino MSMIS Kean University Sequential Searching There is often a need to locate a specific element within an array –Or to determine if an element even exists The simplest method of searching an array is to start at the first element and examine each element in order –This is known as a sequential search
Scott Marino MSMIS Kean University Sequential Search A simple search function –int areacodeexists (int area_code[], int find_area) { int i; for (i = 0; i < num_area_codes; i++) { if (area_code[i] == find_area) { return 1; // true } } // end for loop return 0; // not found }
Scott Marino MSMIS Kean University Sequential Search Invoking the search function cout > input_code; if (areacodeexists(area_code, input_code)) { cout << input_code << “ is valid\n”; } else { cout << input_code << “is not valid\n”; }
Scott Marino MSMIS Kean University Bubble Sort There is often a need to put the elements in an array into a sorted sequence One of the simplest sorting algorithms is the bubble sort The bubble sort works by iterating through the array, swapping elements in the array based upon their values This algorithm is called a bubble sort because the smaller values “float” to the top of the array
Scott Marino MSMIS Kean University Bubble Sort The bubble sort is typically implemented as a nested loop algorithm An early-exit test can be implemented to terminate the looping early if all the elements are in sorted sequence, improving performance
Scott Marino MSMIS Kean University Bubble Sort The bubble sort algorithm: –for (bottom = num_codes - 1; bottom > 0; bottom--) { for (pos = 0; pos < bottom; pos++) { if (area_code[pos+1] < area_code[pos]) { temp_var = area_code[pos+1]; area_code[pos+1] = area_code[pos]; area_code[pos] = temp_var; } // end if } // end inner for } // end outer for
Scott Marino MSMIS Kean University Bubble Sort The outer loop starts one element position from the end of the array –Because the swap algorithm looks at bottom + 1 –For each pass of the outer loop, one element has been swapped to the bottom of the array The inner loop starts at the beginning of the array and swaps elements down until it reaches the current bottom (from the outer loop) of the array –A complete cycle of the inner loop is performed for each iteration of the outer loop
Scott Marino MSMIS Kean University Bubble Sort Swapping two elements requires the use of a temporary variable To swap 2 elements, A and B, the following occurs: –Copy element A to a temporary variable –Copy element B to element A –Copy the temporary variable to element B
Scott Marino MSMIS Kean University Binary Search A binary search is more efficient than a sequential search A binary search is done on an ordered (sorted) array and works by a continual halving and compare algorithm The larger the array the more apparent the benefit of a binary search Binary searches are usually recursive algorithms –The binary search function calls itself
Scott Marino MSMIS Kean University Multi-Dimensional Arrays Arrays can have multiple dimensions Sometimes know as an array of arrays –int matrix[2] [4] = { {1, 3, 5, 7} {10, 20, 30, 40} }; –Creates an array of dimension 2 that is an array of dimension 4
Scott Marino MSMIS Kean University Pointers There are “things” and “pointers to things” Every thing has a memory address in the computer Pointers point to the memory addresses in the computer int thing; /* define a thing */ int *thing_ptr; /define a pointer to thing */
Scott Marino MSMIS Kean University Pointers Pointer operators * - Dereference (given a pointer, get the thing referenced) & - Address of (given a thing, point to it)
Scott Marino MSMIS Kean University Pointers Pointer Syntax –thing - Simple thing (variable) –&thing - Pointer to variable thing –thing_ptr - Pointer to an integer (not necessarily thing) –*thing_ptr - Integer
Scott Marino MSMIS Kean University Linked Lists A linked list is a chain of items where each item points to the next item in the chain Very flexible because the size changes with the number of elements A linked list structure is implemented as a structure with data and pointer to the next element
Scott Marino MSMIS Kean University Homework Write a program that creates an array of 999 elements Using the random number function, generate a random integer for each of the 999 elements Write program code to determine the mean (average), and median values for all the elements in the array
Scott Marino MSMIS Kean University Homework average (mean) = sum total of all values / number of elements median = in an ordered list of elements, this is the element that falls in the exact middle of the list –Odd number of elements - the value at position (number of elements / 2) + 1 –Even number of elements - average of the 2 middle elements - The value at position (number of elements / 2) + ((number of elements / 2) + 1) / 2
Scott Marino MSMIS Kean University Homework Run the program 5 times and print the 5 results Turn in program and results