Chapter 12: Arrays Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey
Current Options for Storing Data 1) You need to store the room temperature, such as 62.5, in a variable. What would you use? a variable of type double, such as double roomtempf = 62.5; 2) You need to store all the attributes for an automobile (such as color, mileage, engine type, cost) in a variable. What would you use? an object of class Car, such as: Car auto = new Car(Color.red,42,"hybrid", 20000); you would have to define the Car class yourself 1-2
A new need, storing many of one type 3) You need to store the high temperature every day for the last year, what would you use? an array of double, such as double [] dailyhigh = new double[365]; 4) You need to store the inventory of all 1200 cars you're trying to sell, what would you use? an array of class Car, such as: Car [] inventory = new Car[1200]; 1-3
Review: Two Ways of Representing Information in Java Primitive types a single quantity int x = 6; x 6 Object types a single entity with multiple attributes Point center= new Point(1,8); 1-4
Arrays: a third way of representing information An array is a set of values where each value is identified by an index. array elements int size = 6; array index 1-5
Access Array Elements using the [ ] operator Note: as with String, elements go from 0 to 3 count[4] = 2; ArrayOutOfBounds Execption What does this do? count[ count[2] ] = 5; 1-6
Using a Loop (Traversal) to print all the items Standard while loop i goes from 0 to 3 When i gets to 4, loop condition fails, exit count[4] is not accessed 1-7
For Loops Has same components as while loop More compact, all control info in header The general syntax looks like this: Equivalent to this while loop: 1-8
Example: For vs While Loop This for loop Works the same as this while loop 1-9
Array Length All arrays have one named instance variable: length Holds the size of the array how many items it can store better to use length field as upper bound of loop last time body of loop is executed is when i = count.length 1 (position of last element) 1-10
Array Initialization When relatively few items need to be initialized, an initialization list can be used to initialize the array. int[] highs = {65, 69, 72, 78, 61 }; The numbers in the list are stored in the array in order: highs[0] is assigned 65, highs[1] is assigned 69, highs[2] is assigned 72, highs[3] is assigned 78, highs[4] is assigned 61. 8-11
Review: The Scanner Class To read input from the keyboard we can use the Scanner class. The Scanner class is defined in java.util, so we will use the following statement at the top of our programs: import java.util.scanner; To create a Scanner object: Scanner keyboard = new Scanner(System.in); 2-12
Read from keyboard with Scanner Examples read the next word (til next white space) as String String word = keyboard.next(); read to the end of the line as a String String line = keyboard.nextline(); read the next number as an int int x = keyboard.nextint(); read the next number as a double double y = keyboard.nextdouble(); 2-13
Do Lab 12 Part A (Problems 1 through 5) 1-14
Checkpoint
Checkpoint int [] employeenumbers = new int[100]; double [] payrates = new double[25]; 0 to 3 1 2 3 4 5
Checkpoint
Checkpoint result = numbers1[0]*numbers2[3]; for (int k=0; k<array.length; k++) array[k]=-1;
Copying Arrays wrong way x Creates one array of three doubles Copies reference to array from variable a to b Doesn't make a separate copy A form of aliasing Change in one array show up in the other 1-19
Side effects of Aliasing a[1] = 8.1; System.out.println( b[1] ) // prints 8.1 b[2] = 3.4; System.out.println( a[2] ) // prints 3.4 8.1 3.4 1-20
Copying Arrays Right Way 1-21
Using a For Loop to do the same For loop that uses the length of a as the size: 1-22
Arrays and Objects In many ways, arrays behave like objects: When you declare an array variable, you get a reference to an array. You have to use new to create the array itself. When you pass an array as an argument, you pass a reference, which means that the invoked method can change the contents of the array. 1-23
Difference between a Rectangle A Rectangle object and an Array of 4 int? Change first value in Rectangle box.x = 25; // fields referred to by name 1-24
Difference between a Rectangle and an Array of 4 int? An Array of 4 int elements: int [] box = {0,0,100,100}; Change first value in box array: box[0] = 25; // elements referred to by index 1-25
Another difference: Array elements must all have same type Objects of class Tile have a char and an int class Tile { } char letter; int value; An array can only hold all char data or all int data, not both, so this could not be represented using an array. 1-26
Do Lab 12 Part B (Problems 6-8) 1-27
Random Numbers Most computer programs are deterministic do the same thing each time they run usually a good thing same calculation should give the same result Some applications need to be unpredictable Games, modeling complicated systems (weather) Sources of truly random numbers: http://qrng.anu.edu.au/ 1-28
Assignment 12 The following slides are to help you visualize the goal of the code you are writing in assignment 12. 1-29
Pseudorandom Numbers We can make computers seem nondeterministic generate numbers using a math formula built into Math.random method code to print 10 pseudorandom numbers: 1-30
Math.random method 1-31
Arithmetic with Random Numbers What if you print x *10? 10 + x? (int) (x*6) + 1; 1-32
Assignment 12 problem 2 Write a method randomint(int low, int high) returns a random number between low (inclusive) and high (exclusive). Math notation: [low, high) randomint(15, 20) produces 15 19 randomly 1-33
Method to create a random array // in main: int [] arr = randomarray(8); 1-34
Method to print an array // in main: int [] arr = randomarray(8); printarray( arr ); 1-35
Counting Suppose the array arr contains test scores: 98 86 79 90 89 88 88 97 92 90 87 69 66 60 86 85 84 77 53 90 79 90 87 74 How many A's were there? How many B's? int counta = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] >= 90) counta++; } 1-36
A method that counts how many values an array has in a given range // in main int numas = inrange( arr, 90, 101); int numbs = inrange( arr, 80, 90); notice, no {} needed when only 1 statement in if statement true block 1-37
Number of Tests Histogram of Test 2 Scores int [ ] scores = {98, 86, 79, 90, 89, 88, 88, 97, 92, 90, 87, 69, 66, 60, 86, 85, 84, 77, 53, 90, 79, 90, 87, 74}; Test Score process scores array into a second array that holds the counts for each possible test score 1-38
One way to create a Histogram Make a separate variable for each count? int count0 = inrange(scores, 0, 1); int count1 = inrange(scores, 1, 2); int count2 = inrange(scores, 2, 3);... int count99 = inrange(scores, 99, 100); painful! How about an array to hold all the counts? 1-39
Better way to create a Histogram Make an array to hold all the counts! int[] counts = new int[100]; for (int i = 0; i < counts.length; i++){ counts[i] = inrange(scores, i, i+1); } Note variable i being used to index counts AND provide limits to inrange How many times do we have to traverse the scores array? 1-40
More efficiently create a Histogram Use the test score itelf as the index to counts! int[] counts = new int[100]; for (int i = 0; i < scores.length; i++){ int index = scores[i]; counts[index]++; } only makes one pass through scores array runs much faster: O(n) vs O(n 2 ) 1-41
Draw a Histogram bar chart int [] arr = { 4,2,4,2,1,2,0,3,0,0,1,2,2}; int [] counts; < make a histogram of arr > [0] XXX [1] XX [2] XXXXX [3] X [4] XX After you've processed data from arr into counts Make a for loop that repeats the number of elements in counts array print the index, then on same line, call bar on counts[index] to print row of X's 1-42
A method that prints a horizontal bar bar(5); // bar(8); // prints XXXXX prints XXXXXXXX pseudocode: method bar, takes parameter length loop that repeats length times print 1 "X" to console after loop, go to new line (println) 1-43
Sorting Arrays [Optional] Computer scientists often need to sort arrays Why? Because it s easier to find things in the array when it is sorted Most data looks better displayed in sorted form (phone books, employee records, Lacrosse games) How can we sort an array? What is the algorithm? A: There are several!! 44
Bubble Sort Bubble sort is one of the simplest sorting algorithms It proceeds through a sequence of iterations, each time moving the next largest item into its correct position On each iteration, it compares each pair of consecutive elements, moving the larger element up 45
Bubble Sort data 0 1 2 3 55 22 99 66 55 46
Bubble Sort data 0 1 2 3 55 22 99 66 if (data[k] > data[k+1]) > 55? 47
Bubble Sort data 0 1 2 3 55 22 99 66 swap(data, k, k+1); swap 48
Bubble Sort data 0 1 2 3 22 55 99 66 55 49
Bubble Sort data 0 1 2 3 22 55 99 66 > 55? 50
Bubble Sort data 0 1 2 3 22 55 99 66 99 51
Bubble Sort data 0 1 2 3 22 55 99 66 > 99? 52
Bubble Sort data 0 1 2 3 22 55 99 66 swap 53
Bubble Sort data 0 1 2 3 22 55 66 99 Notice how the data bubbles up through the array moving slowly, one bin at a time After N-1 Passes or Sweeps, the final array is guaranteed to be sorted in ascending order, no matter what input data 54
Selection Sort Another way of sorting is the selection sort The main idea is to keep finding the smallest (and next smallest) items in the array And move them into correct position (swap) 55
Selection Sort data 0 1 2 3 55 22 99 66 smallest 55 small_pos 0 k 0 55 < smallest? F 56
Selection Sort data 0 1 2 3 55 22 99 66 smallest 55 small_pos 0 k 0 22 < smallest? T 57
Selection Sort data 0 1 2 3 55 22 99 66 smallest 22 small_pos 1 k 0 22 < smallest? T 58
Selection Sort data 0 1 2 3 55 22 99 66 smallest 22 small_pos 1 k 0 99 < smallest? F 59
Selection Sort data 0 1 2 3 55 22 99 66 smallest 22 small_pos 1 k 0 66 < smallest? F 60
Selection Sort SWAP data 0 1 2 3 55 22 99 66 smallest 22 small_pos 1 k 0 swap(data, k, small_pos); 61
Selection Sort Repeat 0 1 2 3 22 55 99 66 smallest 55 small_pos 1 k 1 55 < smallest? F 62
Swapping two array elements public static void swap( int [] arr, int j, int k) { int temp = arr[j]; arr[j] = arr[k]; arr[k] = temp; } 1-63