Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal
Lesson Goals Understand what an array is Understand how to declare arrays Understand what reference variables are Understand how to pass arrays to methods Understand basic sorting Understand linear and binary searching Understand multi-dimensional arrays 2
Fundamentals (1) An array is an object that is used to store a list of values. Each array is made out of a contiguous block of memory that is divided into a number of cells. Each cell holds a value, and all the values are of the same type. Sometimes the cells of an array are called slots. In the example array pictured at right, each cell holds an int. The name of this array is data. The cells are indexed 0 through 9. Each cell can be accessed by using its index. For example, data[0] is the cell which is indexed by zero (which contains the value 23). data[5] is the cell which is indexed by 5 (which contains the value 14). data is not only the name of the array, it is a reference variable which refers to the beginning of the array. In other words, it contains an address 3
Fundamentals (2) The cells in an array are numbered sequentially starting at zero. This is called zero based indexing. If there are N cells in an array, the indexes will be 0 through N-1 Sometimes the index is called a subscript. The expression data[5] is usually pronounced "data-sub-five The value stored in a cell of an array is sometimes called an element of the array. An array has a fixed number of cells, but the values placed in those cells (the elements) may change over time. Every cell of an array holds a value of the same type. So, for example, you can have an array of int, an array of double, and so on. 4
Reference Variables There are two types of variables in Java primitive and reference Primitive variables are byte, short, int, long, double, float, boolean and char Reference variables hold memory addresses Declaring an array in Java creates a reference variable i.e. boolean[] truthful Instantiating the array creates an actual reference to a block of memory boolean []truthful = new boolean [5]; truthful is a reference variable that holds an address, not a boolean value truthful[0] would hold a boolean value at the first address in the array The above example creates 5 boolean cells truthful[0] truthful[4] 5
Declaring Arrays An array is a named sequence of contiguous memory locations capable of holding a collection of data of the same type In order to use arrays, you must learn the basic syntax You can declare an array reference variable in two ways: type[] name or type name[] The first format is more typically used Examples: int[] myarray - an array of type int called myarray double[] numbers an array of type double called numbers 6
Array Instan<a<on There are several ways to instantiate an array. All require using the new operator Declare and instantiate in two statements type[] name; double[] earnings; name = new type[size] ; earnings = new double[6]; Declare and instantiate in one statement type[] name = new type[size]; double[] earnings = new double[6]; Declare, instantiate and initialize in one statement type[] name = v 0, v 1, v 2 v n-1 ; double[] earnings = 25.2, 35.9, 72.6, 12.8, 176.4, 99.0; This example creates an array called earnings of length 6 7
Array Instan<a<on Basic Rules The values in an array must all be of the same data type The first index in the array is 0 An array is referenced from name[0] name[length-1] The elements of an array are always initialized to 0 by type boolean arrays are initialized to false char initializes to the null character Any reference type initializes to null 8
Instant Check Write the statement(s) necessary to instantiate: - a boolean type honesty with size 7 - a short type days with size 365 9
Answers boolean [ ] honesty = new boolean[7]; short [] days = new short[365]; 10
Array Length The length of an array is how many cells it has. An array of length N has cells indexed 0..(N-1) The length is a variable associated with the object Example: int [] testarray = new int [10]; Then testarray.length equals 10 You get the length value with every array that is instantiated. It is an instance variable associated with the object Note: There is also an Arrays class which has lots of methods for manipulating an array object. You can look at this but we won t be using until we learn more about objects. http://docs.oracle.com/javase/7/docs/api/java/util/arrays.html 11
Bound Checking in Arrays Indexes must be an integer type greater than or equal to 0 and less than length. If an expression is always illegal it will be caught at compile time However, if an index is found to be illegal during execution an exception message will appear and the program is terminated 12
Bound Checking in Arrays - Examples Given: int[] data = new int[10]; Example Outcome data[ -1 ] always illegal index must be >= 0 data[ 10 ] data[ 1.5 ] data[ 0 ] data[ 9 ] data[ j ] illegal out of range (given the above declaration) always illegal must be an integer always OK OK (given the above declaration) can't tell (depends on the value of j) 13
Using an Expression as an Index class ArrayExample01 public static void main ( String[] args ) double[] val = new double[4]; val[0] = 0.12; val[1] = 1.43; val[2] = 2.98; int j = 3; System.out.println( "cell 4: " + val[ j ] ); System.out.println( "cell 3: " + val[ j-1 ] ); j = j-2; System.out.println( "cell 2: " + val[ j ] ); 14
Copying Values from Cell to Cell versus Crea<ng Two References to the Same Object public class ArrayExample02 public static void main ( String[] args ) int[] vala = 12, 23, 45, 56 ; int[] valb = new int[4]; //a new array valb[ 0 ] = vala[ 0 ] ; valb[ 1 ] = vala[ 1 ] ; valb[ 2 ] = vala[ 2 ] ; valb[ 3 ] = vala[ 3 ] ; int [ ] valc ; valc = valb; for (int i=0; i<vala.length; i++) System.out.println(valA[i]); for (int i=0; i<valb.length; i++) System.out.println(valB[i]); for (int i=0; i<valc.length; i++) System.out.println(valC[i]); System.out.println((valA==valB)); //this is false System.out.println((valA==valC)); //this is false System.out.println((valB==valC)); //this is true System.out.println((valA[0] == valb[0]) && (vala[0] == valc[0]) && (valb[0] == valc[0])); //this is true 15
Visualizing the Previous Program vala 12 valb 12 valc 23 23 45 45 56 56 16
Arrays and Methods(1) Passing an Array to a Method An array reference can be passed as a parameter to a method This allows all the current values of the array to be obtained for use by the method Example: Method Header: public static void swap(int[] x, int i, int j) In the body of main: int[] list = 1,3,5,7,9; swap(list, 2, 4) sends the address of the array list to x, as well as the values of i and j Within the method x can reference 5 successive integers, the same as those in list. It is referring to the same place. Therefore it can change that array. Even though the variable x only exists in the swap method, the changes made to the array are persistent and visible in the calling method, since it is referencing to the same array. 17
Arrays and Methods(2) Passing an Array to a Method public class ArraySwapper public static void swap(int[] x, int i, int j) int temp = x[i]; x[i] = x[j]; x[j] = temp; public static void main(string[] args) int [] list = 1,3,5,7,9; System.out.print("Before: "); for (int i=0; i<list.length; i++) System.out.print(list[i] + " "); swap(list,2,4); System.out.print("\nAfter:"); for (int i=0; i<list.length; i++) System.out.print(list[i] + " "); 18
Arrays and Methods (3) Passing an Array from a Method The value of the method can be a reference to an array created in the method If the method returns a reference then it must return the reference to an array of like type. Why??? However, you don t need to create a new array, just declare the reference variable in the calling routine that accepts the reference. There is only one array, not two. 19
Arrays and Methods (4) Passing an Array from a Method public class ArrayPassing public static double[] returnarray( ) double[] x; //creating a reference variable x = new double[3]; // Create an array of 3 elements x[0] = 2.3; x[1] = 3.4; x[2] = 4.5; return( x ); // Return the **reference** (location) of the array public static void main (String[] args) double [ ] a; /here a.length does not exist a = returnarray(); for (int i=0; i < a.length; i++) // now a.length does exist System.out.println(a[i]); 20
Why Arrays? Using arrays allows us to reference large amounts of data by index. With a single name we can store and access a large number of elements, sorting, searching and organizing them For instance, instead of listing grade0, grade1, grade2, grade3, grade4,. You can just loop through an array called grade using grade[0], grade[1], grade[2], grade[3], grade[4],... With arrays and looping we have combined two powerful weapons of programming 21
Using Arrays - Popula<ng an Array public class ArrayDemo public static void main(string[] args) int[] anarray; // DECLARE a reference for an array of integers anarray = new int[10]; // CREATE an array of integers // assign a value to each array element for (int i = 0; i < anarray.length; i++) anarray[i] = i; // print a value from each array element for (int i = 0; i < anarray.length; i++) //anarray.length is variable equal to the size of the array System.out.print(anArray[i] + " "); System.out.println(); 22
Using Arrays - Popula<ng an Array with a RunTime Array Length import java.util.scanner; public class ArrayDemo2 public static void main(string[] args) int size; int[] anarray; // DECLARE a reference for an array of integers Scanner keyboard = new Scanner(System.in); System.out.print("Input size of the array: "); size= keyboard.nextint(); anarray = new int[size]; // CREATE an array of integers // assign a value to each array element for (int i = 0; i < anarray.length; i++) anarray[i] = i; // print a value from each array element for (int i = 0; i < anarray.length; i++) //anarray.length is variable equal to the size of the array System.out.print(anArray[i] + " "); System.out.println(); Deciding the size of the array in real-time allows the program to be more efficient and flexible it is data driven rather than hard-coded There are other types of array like objects that allow for more dynamic lists also known as queues 23
Using Arrays - Finding The Maximum Number in an Array import java.util.scanner; public class ArrayMax public static void main(string[] args) int size, max_value; int[] anarray; // DECLARE an array of integers Scanner keyboard = new Scanner(System.in); System.out.print("Input size of the array: "); size= keyboard.nextint(); anarray = new int[size]; // CREATE an array of integers dynamically //read in an array for (int i=0; i < anarray.length; i++) System.out.println("Enter integer value for anarray(" +i +")"); anarray[i] = keyboard.nextint(); max_value= anarray[0]; for (int i = 1; i < anarray.length; i++) if (anarray[i] > max_value) max_value = anarray[i]; // print the maximum System.out.print("The maximum value of the array is: " +max_value + \n ); Now write a program to find the minimum value in an array. Then write a program that sums the numbers in an array 24
Using Arrays - Finding The Average of the Numbers in an Array import java.util.scanner; public class ArrayAverage public static void main(string[] args) int size, sum; long average; int[] anarray; // DECLARE an array of integers Scanner keyboard = new Scanner(System.in); System.out.print("Input size of the array: "); size= keyboard.nextint(); anarray = new int[size]; // CREATE an array of integers dynamically //read in an array for (int i=0; i < anarray.length; i++) System.out.println("Enter integer value for anarray(" +i +")"); anarray[i] = keyboard.nextint(); sum= 0; for (int i = 0; i < anarray.length; i++) sum = sum + anarray[i]; average = Math.round((double)(sum)/anArray.length); System.out.print("The average value of the array is: " +average + "\n"); 25
SorDng Sorting is a method for reorganizing a list from top to bottom or bottom to top There are many different algorithms for sorting In order to search a list it is often easier to first sort it A random list can only be searched directly by going through the list one element at a time unless you sort it firsy Alphabetizing is also a type of sorting that we can learn after we study the String class We will look at the insertion method of sorting 26
Using Arrays - Sor<ng import java.util.scanner; public class ArraySorter public static void main(string []args) int size, swap; Scanner in = new Scanner(System.in); System.out.println("Input number of integers to sort"); size = in.nextint(); int array[] = new int[size]; System.out.println("Enter " + size + " integers"); for (int c = 0; c < size; c++) array[c] = in.nextint(); for (int c = 0; c < ( size - 1 ); c++) for (int d = 0; d < size - c - 1; d++) if (array[d] > array[d+1]) /* For descending order use < */ swap = array[d]; array[d] = array[d+1]; array[d+1] = swap; System.out.println("Sorted list of numbers"); for (int k = 0; k < size; k++) System.out.println(array[k]); System.out.println(); 27
Using Arrays Sor<ng How Does the Inser<on Method Work Assume the list is array[0] =15 array[1] = 14 array[2] = 13 array[3] = 12 after first round we have 14 13 12 15 after second round 13 12 14 15 after third round 12 13 14 15 c d array[d] array[d+1] swap 0 0 15 14 15 14 15 0 1 15 13 15 13 15 2 15 12 15 12 15 1 0 14 13 14 13 14 1 1 14 12 14 12 14 2 0 13 12 13 12 13 28
Using Arrays - Search Linear Search Linear search is a method for searching one by one through a list until you find a match It is somewhat laborious For larger lists it becomes very inefficient Review ArrayLinearSearch.java for example Binary Search Requires that the list is ordered you can order the list first Simply keep dividing the list in half until you find the number Review ArrayBinarySearch.java 29
Efficiency of Binary Search n Average linear = n/2 Average binary = log 2 n -1 4 (2 2 ) 2 2 16 (2 4 ) 8 3 1024 (2 10 ) 512 9 1048576 (2 20 ) 524288 19 30
Two-Dimensional Arrays A two dimensional array is like a table or a matrix It has rows and columns In java, both the rows and columns are indexed starting at zero A two-dimensional array is actually an array of arrays As with one-dimensional arrays all values of the array must be of the same type The reference is always first by row and then column - array [row] [column] Array [0][0] Array [0][1] Array [0][2] Array [0][3] Array [1][0] Array [1][1] Array [1][2] Array [1][3] Array [2][0] Array [2][1] Array [2][2] Array [2][3] Array [3][0] Array [3][1] Array [3][2] Array [3][3] Array [4][0] Array [4][1] Array [4][2] Array [4][3] 31
Declaring Two-Dimensional Arrays (1) Both the two-step and one step methods are available Two-steps: int[][] table; // declares the variable table = new int[2][3]; //instantiates the array One step: int[][] table = new int[2][3] It can be processed by row or by column Either way it looks like this, with all values initialized to 0: 0 1 2 0 0 0 0 1 0 0 0 32
Declaring Two-Dimensional Arrays (2) You can also explicitly declare a matrix by rows: int[][] gradetable = 99, 42, 74, 83, 100, 90, 91, 72, 88, 95, 88, 61, 74, 89, 96, 61, 89, 82, 98, 93, 93, 73, 75, 78, 99, 50, 65, 92, 87, 94, 43, 98, 78, 56, 99 Using this method you can create rows with uneven numbers of entries (advanced subject) row Col 0 1 2 3 4 0 99 42 74 83 100 1 90 91 72 88 95 2 88 61 74 89 96 3 61 89 82 98 93 4 93 73 75 78 99 5 50 65 92 87 94 6 43 98 78 56 99 33
Simple Example of a Useful Table Student Week 0 1 2 3 4 0 99 42 74 83 100 1 90 91 72 88 95 2 88 61 74 89 96 3 61 89 82 98 93 4 93 73 75 78 99 5 50 65 92 87 94 6 43 98 78 56 9 The table has 7 rows and 5 columns the headers are not part of this table 34
Finding the Number of Rows and Columns of Arrays With Unequal Length Ragged Arrays The length of a two-dimensional array is its number of rows Array.length The number of columns in a row is Array[row].length In matrix below: Array.length = 5 Array[0].length = 4; Array[1].length = 3; Array[2].length = 4; Array[3].length = 2; Array[4].length = 4; Array [0][0] Array [0][1] Array [0][2] Array [0][3] Array [1][0] Array [1][1] Array [1][2] Array [2][0] Array [2][1] Array [2][2] Array [2][3] Array [3][0] Array [3][1] Array [4][0] Array [4][1] Array [4][2] Array [4][3] 35
Declaring An Array With Unequal Column Entries int [][] array = new int [4][]; array[0] = new int[5]; array[1] = new int[1]; array[2] = new int[1]; array[3] = new int[4]; Remember We are declaring an Array of Arrays 36
Declaring Two-Dimensional Arrays With Uneven Numbers of Columns during Popula<on You can also explicitly declare a matrix by rows: int[][] gradetable = 99, 42, 74, 90, 91, 72, 88, 95, 88, 61, 89, 82, 98, 93, 73, 75, 78, 99, 50, 65, 92, 87, 94, 43, 98 Using this method you can create rows with uneven numbers of entries (advanced subject) gradetable.length = 7 gradetable[0].length = 3 gradetable[1].length = 5 gradetable[2].length = 1 gradetable[3].length = 4 gradetable[4].length = 5 gradetable[5].length = 5 gradetable[6].length = 2 row Col 0 1 2 3 4 0 99 42 74 1 90 91 72 88 95 2 88 3 61 89 82 98 4 93 73 75 78 99 5 50 65 92 87 94 6 43 98 37
Prin<ng a Two-Dimensional Array class ArrayPrint2D public static void main( String[] args ) // declare and construct a 2D array int[][] myarray = 1, 9, 4, 6, 0, 2,4,5, 0, 1, 2, 3 ; // print out the array for ( int row=0; row < myarray.length; row++ ) System.out.print("Row " + row + ": "); for ( int col=0; col < myarray[row].length; col++ ) System.out.print( myarray[row][col] + " "); System.out.println(); 38
Programming Exercises Class (1) Exercise 1 Array Data Write two methods that read data from the console and store the data in an array: a. The method int readdata(int[] x) reads a list of at most 100 integers into the array x. A sentinel, -999, terminates the list. The method returns the size of the list. b. The method int[] readdata() reads and returns a list of integers. The list is preceded by the number of the items in the list. For example, the data 6 9 7 5 3 1 2 indicates that there are six items in the list. The leading 6 is not included in the list. Test both these methods within a single program that includes a method: void printlist(int [] x, int n) that displays x(0) through x(n-1) 39
Programming Exercises Class (2) Exercise 14 Max Sort Implement a method void maxsort(int[] x, int size) // that sorts the partially filled array x. The method maxsort( ) first determines the largest value in x and swaps that value with x[size-1]; then maxsort( ) finds the next largest value and swaps that value with x[size-2], and so on. Include an auxiliary method int max(int[] x, int i) that returns the index of the largest element between x[0] and x[i] inclusive. Test your methods in a program. 40
Programming Exercises Class (3) Exercise PrintArrays Implement a method readarr that accepts a reference to a two dimensional integer array and reads in values for all the cells of the array Implement a method writearr that accepts a reference to a two dimensional array and prints out all the cells of the array row by row. Implement a main method that creates 2 twodimensional arrays, by reading in the number of rows and columns and creating the array. For each array call the two methods defined above. 41
Programming Exercises Lab (1) Exercise 9 Largest and Smallest Design a method that determines the largest and smallest values stored in an integer array x. Your method should return these values in an array of length 2. Use the following algorithms: Initialize variables currentbig and currentsmall to the larger and smaller values of x[0] and x[1]. Process the rest of the list two elements at a time. Compare the larger of the two elements to currentbig and replace currentbig if necessary. Compare the smaller of the two elements to currentsmall and replace currentsmall if necessary. Test your method in a program and include a method that reads a list, terminated by -999, into an array. 42
Programming Exercises Lab (2) Exercise 15 Selection Sort Implement a method void selectionsort(int[ ] x, int size) // (size <= x.length) that sorts the partially filled array x. The method selectionsort( ) first determines the smallest value in x and swaps that value with x[0]; then selectionsort( ) finds the next smallest value and swaps that with x[1] and so on. Include an auxiliary method int min(int[ ] x, int i) that returns the index of the smallest element between x[i] and x[size-1], inclusive. Test your methods in a program. 43