1 / 57

Introduction To Scientific Programming

Introduction To Scientific Programming. Chapter 6 – Arrays. Lecture Overview on Arrays. Array Basics Arrays in Classes and Methods Sorting & Searching Arrays Multidimensional Arrays. I. Array Basics. An array is a single name for a collection of data values (all of the same data type)

bud
Download Presentation

Introduction To Scientific Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction To Scientific Programming Chapter 6 – Arrays

  2. Lecture Overview on Arrays • Array Basics • Arrays in Classes and Methods • Sorting & Searching Arrays • Multidimensional Arrays

  3. I. Array Basics • An array is a single name for a collection of data values (all of the same data type) • A special subscript notation identifies precisely one of the values of the collection • Arrays work like objects: • They are initialized like objects • There can be multiple arrays of the same type • Arrays are a natural fit for loops, especially for loops • However, they are not “full” objects • No real methods, constructors, or “inheritance”

  4. Creating Arrays • General syntax for declaring an array: Base_Type[] Array_Name = new Base_Type[Length]; • Examples: 80-element array with base type char:char[] symbol = new char[80]; 100-element array with base type double:double[] reading = new double[100]; 100-element array with base type AddressBook:AddressBook[] homebook = new AddressBook[100];

  5. Three Uses of [ ] (Brackets)with an Array Name 1. To create an array type name, e.g. int[] pressure; creates a name with the type "int array" • The types int and “int array” are different 2. To create a new array, e.g. pressure = new int[100]; 3. To name a specific element in the array (also called an indexed variable), e.g. pressure[3] = SavitchIn.readLineInt(); System.out.println("You entered" + pressure[3]);

  6. An Array Declaration Can Be “Broken-Up” • Last slide syntax was correct! Why? Because you can break up declaration like any object • For example, the complete declaration: int[] pressure = new int[100]; can be broken up into: int[] pressure; //first part declaration … pressure = new int[100]; //second part assignment … • This can be handy for re-declaration (more on this soon).

  7. Array Terminology Array name temperature[n + 2] temperature[n + 2] temperature[n + 2] temperature[n + 2] = 32; Index (also called a subscript) - Must be an int, or an expression that evaluates to an int Indexed element/variable (also called a subscripted variable) Value of the indexed variable (also called an element of the array) Note: an "element" may refer to either a single indexed variable in the array or the value of a single indexed variable.

  8. Array Length • The length of an array is specified by the number given in the brackets when it is created with new • This determines the maximum number of elements the array can hold and the amount of memory allocated for the elements • The array length can always be read with the instance variable length. • E.g. the following code displays the number 20 (this is the size, or length of the double array, entry): double[] entry = new double[20]; //20*8 bytes allocated System.out.println(entry.length); • The length attribute is established in the declaration and cannot be changed by the programmer unless the array is re-declared.

  9. Subscript Range • Any array subscript uses “zero-numbering” • The first element has subscript 0 • The second element has subscript 1 • The nth element has subscript n-1 • The last element has subscript length-1 • For example: int[] score = new int[4]; … (Score is assigned values 97, 86, 92, and 71) … Configuration:

  10. Subscript Issues & The “Out of Bounds” Error • Using a subscript larger than length-1 causes a run-time (not a compiler) error • An ArrayOutOfBoundsException is thrown • You need to fix the problem and recompile • Some other programming languages (most noticeably C and C++) do not even cause a run time error! • It is a dangerous characteristic (of any language) to allow out of bounds array indexing. • Why? Because bounds checking requires extra overhead. • The most sophisticated compliers have the option to turn bounds checking on and off.

  11. Initializing an Array's Valuesin Its Declaration • Array declaration syntax allows element initialization by using a comma-delimited list in curly braces. • To initialize an array, drop everything right of the equal sign and add the value list. • For example: int[] score = {97, 86, 92, 71}; • The length of an array is automatically determined when the values are explicitly initialized in the declaration. • If an array is un-initialized, all elements will be assigned some default value, e.g. 0 for int arrays.

  12. Initializing Array Elements in a Loop • Array processing is most commonly done in a loop. • A for loop is commonly used to initialize/work with arrays and array elements. • Example: int i; //loop counter & array index int[] a = new int[10]; … For (i = 0; i < a.length; i++) a[i] = 0; • The loop counter/array index goes from 0 to length – 1 • Loop counts through 10 iterations using the zero-numbering of the array index (0-9).

  13. Array Programming Tips • Use singular rather than plural names for arrays unless the data itself is plural. This improves readability. • For example: System.out.println(“The top score=” + score[index]); • This is because, although the array contains many elements, an array used with a subscript references a single value. • Do not count on default initial values for array elements • You should explicitly initialize elements in the declaration or most commonly in a loop at the beginning of a method.

  14. II. Arrays in Classes and Methods • Arrays and array elements can be used with classes and methods just like other objects. • Both an indexed array element and an array name can be an argument in a method. • Both an indexed array element and an array name can be returned by a method.

  15. An Indexed Array Element As A Method Argument public static void main(String arg[]) { int i, firstScore; int[] nextScore = new int[3]; double possibleAverage; System.out.println("Enter your score on exam 1:"); firstScore = SavitchIn.readLineInt(); for (i = 0; i < nextScore.length; i++) nextScore[i] = 80 + 10*i; for (i = 0; i < nextScore.length; i++) { possibleAverage = ave(firstScore,nextScore[i]); System.out.println("If your score on exam 2 is " + nextScore[i]); System.out.println(" your average will be " + possibleAverage); } } public static double ave(int n1, int n2) { return (n1 + n2)/2.0; } nextScore is an array of int an element of nextScore is an argument of method average average method definition

  16. When Can a Method Change an Indexed Array Element Argument? • When an array element is a primitive type: • A copy of the value is passed as an argument in method call • So, the method cannot change the value of the indexed array element • This follows the “call-by-value” convention • When an array element is a class type: • The address of the object is passed as an argument in method call • So, the method can change the value of the indexed array element • This follows the “call-by-reference” convention • Note: the corresponding argument in the method definition becomes just another name for the object

  17. Array Names as Method Arguments • When you want to pass an entire array as an argument to a method, just use the array name and no brackets. • As previously described, any method that gets a non-primitive type (the entire array, in this case) has access to the original array and can change the value of its’ elements. • Using the length attribute inside the method will handle needing to know the size of the array and avoid ArrayIndexOutOfBoundsException

  18. Example: An Array as an Argument in a Method Call public static void showArray(char[] a) { int i; for(i = 0; i < a.length; i++) System.out.println(a[i]); } the method's argument is the name of an array of characters uses the length attribute to control the loop allows different size arrays and avoids index-out-of-bounds exceptions

  19. Solving Another Mystery - Arguments for the main Method • The declaration of a program’s main method defines a parameter that is an array of type String: public static void main(String[] args) • When you execute a program from the command line, all words after the class name will be passed to the main method in the args array. • The following main method in the class TestProgram will print out the first two arguments it receives: public static void main(String[] args) { System.out.println(“Options:“ + args[0] + “ “ + args[1]); }

  20. Issues With Reference Types • Consider the following: int[] a = new int[3]; int[] b = new int[3]; • With the code statement b=a; what do you get? • Since a and b are reference types, you get the address ofa assigned to the address ofb (you basically give a the name b). • If you want to copy a to b, you need to use/write a clone method • With the code if(b==a) … what do you compare? • Since a and b are reference types, you check if the address ofa and the address ofb are the same (i.e. are they exact same object). • If you want to check if the arrays are equal, you need to use/write an equals method.

  21. Example: Using = With Array Names int[] a = new int[3]; int[] b = new int[3]; for(int i; i < a.length; i++) a[i] = i; b = a; System.out.println(a[2] + " " + b[2]); a[2] = 10; System.out.println(a[2] + " " + b[2]); The output for this code will be: 2 2 10 10 This does not create a copy of array a;it makes b another name for array a.

  22. Example: Using == With Array Names int i; int[] a = new int[3]; int[] b = new int[3]; for(i; i < a.length; i++) a[i] = i; for(i; i < b.length; i++) b[i] = i; if(b == a) System.out.println("a equals b"); else System.out.println("a does not equal b"); a and b are both 3-element arrays of int all elements of a and b are assigned the value 0 tests if the addresses of a and b are equal, not if the array values are equal The output for this code will be "a does not equal b" because the addresses of the arrays are not equal.

  23. Testing Two Arrays for Equality • To test two arrays for equality you need to define an equals method • Return true if and only the arrays have the same length and all corresponding values are equal • Can you write a clone method now? public static boolean equals(int[] a, int[] b) { boolean match; if (a.length != b.length) match = false; else { match = true; //tentatively int i = 0; while (match && (i < a.length)) { if (a[i] != b[i]) match = false; i++; } } return match; }

  24. Methods That Return an Array • Method vowels returns an array of type char[] • The array newArray is not passed back, the address is passed back. • Notice that the array name within the method is just another name for the original array c. public class returnArrayDemo { public static void main(String arg[]) { char[] c; //typed but not allocated c = vowels(); for(int i = 0; i < c.length; i++) System.out.println(c[i]); } public static char[] vowels() { char[] newArray = new char[5]; newArray[0] = 'a'; newArray[1] = 'e'; newArray[2] = 'i'; newArray[3] = 'o'; newArray[4] = 'u'; return newArray; } } c, newArray, and the return type of vowels are all the same type: char []

  25. Wrapper Classes For Arrays • Arrays can be made into objects by defining them in a class • No special syntax, just define array in a class and add the appropriate structure • Derives name from and similar in structure to wrapper classes for primitive types • In a well-defined array wrapper class, one can: • Make an array an instance variable • Define accessor/mutator methods to read and write element values and parameters • Define constructors • Define .equals, .clone, .toString, .sort, … • This strategy leads to a number of very important data structures that are discussed in Math 108 – linked lists, queues, stacks, hash tables, etc…

  26. Watch For Partially Filled Arrays • Sometimes only part of an array has been filled with valid data • Array elements always contain something, whether you have written to them or not • Elements which have not been written to contain unknown (or garbage) data so you should avoid reading them • There is no automatic mechanism to detect how many elements have been filled – you need to keep track!

  27. entry[0] Buy milk. entry[1] Call home. entry[2] Go to beach. entry[3] " " entry[4] " " countOfEntries - 1 garbage values Example: Partially Filled Array • entry is an array of type String. • countOfEntries is current size (pointer). countOfEntries has a value of 3. entry.length has a value of 5.

  28. III. Sorting an Array • One of the most common issues facing programmers is to sort one or more arrays • You may need to: • Sort numbers in ascending or descending order • Sort characters or strings in alphabetic order • Sort one array and rearrange another based on first sort • There are many algorithms (or methods) to sort an array. Some of the most common are Selection sort, Quicksort, and Heapsort • Sorting algorithms have a number of attributes • Speed/Efficiency, Direction, Order Preservation, In-Place, etc..

  29. Selection Sort • Selection sort is one of the easiest to understand and program • Also, one of the slowest – called O(n2)! • Great for rearranging multiple arrays based on sorting one of them (think email) • Pseudocode for Selection sort: • For each index in the array • Find the smallest value from the current index • Swap current index value with smallest value

  30. Selection Sort:Diagram of an Example Problem: sort this 10-element array of integers in ascending order: 1st iteration: smallest value is 3, its index is 4, swap a[0] with a[4] before: after: 2nd iteration: smallest value in remaining list is 5, its index is 6, swap a[1] with a[6] Etc. - only nine iterations are required since the last one will put the last two entries in place by swapping them if necessary.

  31. Attributes Of Selection Sort • The SelectionSort program in your book shows a class for sorting an array of int in ascending order. • Algorithm attributes: • Every indexed variable must has a value • If the array has duplicate values, they are put in sequential positions (order preserving) • Note: sorting was defined in terms of smaller tasks, such as "find the index of the smallest value" and “swap two elements” • These “subtasks” are written as separate methods and are private because they are helper methods (external users are not expected to call them directly)

  32. Selection Sort Code /************************************************** * Sorts an array of integers. Every indexed * variable of array a has a value. Requires helper * routines indexOfSmallest & swap. * * Output: a[0] <= a[1] <= ... <= a[a.length - 1]. * **************************************************/ public static void sort(int[] a) { int index, indexOfNextSmallest; for (index = 0; index < a.length - 1; index++) { //Find the next smallest value from current position indexOfNextSmallest = indexOfSmallest(index, a); //Place the correct value in a[index] swap(index,indexOfNextSmallest, a); } }

  33. Selection Sort Code - II /************************************************** * Returns an index in array a of the minimum value * from a[startIndex] through a[a.length-1] * **************************************************/ private static int indexOfSmallest(int startIndex, int[] a) { int min = a[startIndex]; //Beginning min value int indexOfMin = startIndex; //Index of beginning min value int index; for (index = startIndex+1; index < a.length; index++) { //Find min from a[startIndex] through a[index] if (a[index] < min) { min = a[index]; indexOfMin = index; } return indexOfMin; }

  34. Selection Sort Code - III /************************************************** * Swaps two elements in array a. * **************************************************/ private static void swap(int i, int j, int[] a) { int temp; temp = a[i]; a[i] = a[j]; a[j] = temp; //original value in a[i] }

  35. Sorting Algorithm Tradeoffs • There is always a tradeoff in sorting algorithms between efficiency and simplicity. • Selection Sort is: • Not very efficient: O(n2) • But, easy to code and make modifications • Quicksort & Heapsort are: • Very efficient: O(nlog(n)) • But, more complicated and harder to modify • Rule of thumb: If you have more than 100 elements, you should always use an efficient sorting algorithm.

  36. Sorting in Java • Sorting is so common that Java provides a library of routines to perform optimized O(nlog(n)) sorting and searching • Import the package java.util.Arrays; • There are a number of static methods to perform in-place sorting and searching, e.g. int[] ivalue = new int[1000]; … Arrays.sort(ivalue);

  37. Bonus II - Selection Sort Code For Multiple Arrays /************************************************** * Sorts two arrays of integers based on sorting a. * Every indexed variable of array a has a value. * Requires helper routines indexOfSmallest & swap. * * Output: a[0] <= a[1] <= ... <= a[a.length - 1]. * Array b is sorted based on a **************************************************/ public static void sort(int[] a, int[] b) { int index, indexOfNextSmallest; for (index = 0; index < a.length - 1; index++) { //Find the next smallest value from current position indexOfNextSmallest = indexOfSmallest(index, a); //Place the correct value in a[index] swap(index,indexOfNextSmallest, a); swap(index,indexOfNextSmallest,b); } }

  38. Searching an Array • An equally common task to sorting an array is to find a particular value in an array. • There are two basic approaches to searching an array for a particular value – sequential search or binary search. • The two main issues with searching: • How many times do you need to search? • What do you do if the value is not found? • An important extension to searching in an array is searching in two-dimensional arrays or tables.

  39. Sequential Search • A sequential search is the easiest to understand and program. • If you are only going to do it once, it is also the fastest! • Sequential search pseudocode: • For each element in the array from the start • If value is equal to current index element, return index • If end of array is reached with no match, return 0 • A sequential search of an array is an O(n) process.

  40. Sequential Search Code /********************************************* * This routine performs a sequential search of * an array of integers. If ivalue is found, * The index is returned. If no match is found, * zero is returned. * * *********************************************/ public int ssearch(int[] a, int ivalue) { int i = 0; for (;i < a.length; i++) { if (a[i] = ivalue) return i; } return 0; }

  41. Sequential Search Code /********************************************* public static void showTable(int[][] displayArray) { int row, column; for (row = 0; row < displayArray.length; row++) { System.out.print((row + 1) + " "); for (column = 0; column < displayArray[row].length; column++) System.out.print("$" + displayArray[row][column] + " "); System.out.println(); } }

  42. Searching An Array Multiple Times • If you need to frequently search for items in an array, sequential searching is inefficient. • A much quicker way is to use binary search. • Binary searching uses a divide and conquer algorithm to quickly locate the value in roughly half the time of a sequential search. This type of searching is an O(n/2) process. • The issue is that a binary search only works on sorted data. So, you must incur the extra overhead of sorting the data first before performing binary searches.

  43. Searching in Java • Java provides a library of routines to perform optimized searching. • Import the same package as before: java.util.Arrays; • To perform multiple, efficient searches: int[] ivalue = new int[1000]; int index1,index2,item1,item2,… ; … Arrays.sort(ivalue); … index1 = Arrays.binarySearch(ivalue,item1); index2 = Arrays.binarySearch(ivalue,item2);

  44. IV. Multi-Dimensional Arrays • The next logical extension to a one-dimensional array is a two-dimensional array and so on… • Java handles multi-dimensional arrays by just adding an index for each dimension (an array’s rank is how many dimensions it has). • A two-dimensional (2-D) array can be thought of as a table, grid, or matrix • The first dimension can be thought of as a row • The second dimension can be thought of as a column • A cell or value is the intersection of a row and a column • An array element corresponds to a cell in the table

  45. Representing A Table As A 2-Dimensional Array • The first dimension or row identifier is Year • The second dimension or column identifier is Percentage • Any cell contains a balance for a year and a percentage rate • Example: the balance for year 4 and rate of 7.00% = $1311 Note: the table assumes a starting balance of $1000

  46. Previous Table As A 2-D Java Array Column Index 4 (5th column) • Generalize structure to two indexes: [row][column] • Each cell contains balance for a year i (row) and a percentage rate j (column) • All indexes use zero-numbering. Hence: • table[3][4] = cell in 4th row (year = 4) and 5th column (7.50%) • table[3][4] = $1311 (shown in yellow) Row Index 3 (4th row) Chapter 11

  47. Java Syntax to Create Multi-Dimensional Arrays • Generalized syntax for an array is: Base_Type[]…[] Array_Name = new Base_Type[Length_1]…[Length_n]; • For example, to declare a 2-D array of float named table from the previous example: float[][] table = new float[5][6]; • You can also break-up the declaration as: float[][] table; Definition table = new float[5][]; table[0] = new table[6]; table[1] = new table[6]; table[2] = new table[6]; table[3] = new table[6]; table[4] = new table[6]; Allocation

  48. Processing a 2-D Array: Nested for Loops • Arrays and for loops are a natural fit • To process all elements of an n-D array, nest nfor loops • Each loop has its own counter that corresponds to an index • For example: populate a 5x6 matrix with values from 1 to 30 • The “inner” loop repeats 6 times for every “outer” loop iteration • The “outer” loop repeats 5 times • The total repeats 6 x 5 = 30 times = # of cells in table int[][] table = new int[5][6]; int row, column, index=0; for (row = 0; row < 5; row++) for (column = 0; column < 6; column++) { index++; table[row][column] = index; }

  49. 0123 0 1 2 Implementation ofMulti-Dimensional Arrays • Multi-dimensional arrays are implemented as arrays of arrays. • Example: int[][] table = new int[3][4]; • table is actually a one-dimensional array of length 3 • Each element in table is an array of int with length 4 • This is called “row-oriented storage”. Why is this important? • To sequentially access elements of a matrix (fastest), you need to loop through the outer most index in the inner most loop. table[0] refers to the first row in the array, which is a one-dimensional array itself.

  50. 0123 0 1 2 Accessing Multi-Dimensional Arrays • The .length variable is valid for multi-dimensional arrays, but be careful! • table.length is the number of rows of the array • table[i].length is the length of the ith row (column length) • Note: drop the outermost index in syntax • Example for table below: • table.length gives length (3) for the number of rows in the array • table[0].length gives length (4) for the length of the row (# of columns) • Can the number of columns ever vary or is table[i].length always the same? table[0].length refers to the length of the first row in the array.

More Related