Chapter 07
Chapter 07
Chapter 7
Arrays and Lists:
One Name for Many Data
Arrays
• type[] name:
• The integer size indicates the length of the array, i.e., the
number of cells in the array.
Array Instantiation
• The values held in an array must all be the same data type.
int [] numberList;
numberList = new double[5];
**********
numberList refers to an array of 5 integers
Each array cell is initialized to 0
Array Instantiation
int x = 3;
char [] letters = new char[2*x];
**********
letters refers to an array of char data.
Each memory cell is initialized to 0.
Array Instantiation
The statement:
• System.out.println(5*numbers[1] + 3*numbers[0]);
Using an Array
Program statement:
• Write a program that prompts for 10 integers and displays those same numbers
in reverse order. For example, if you enter the numbers:
0 11 2 33 4 55 6 77 8 99
99 8 77 6 55 4 33 2 11 0
Solution
Lines 11 and 12: for (int i= 0; i < 10; i++) list[i] = input.nextInt();
The for loop prints the array items in reverse.: list[9], list[8],
…, and list[0].
Array Initialization
char letters[] ;
letters = new char[3];
letters[0] = 'a';
letters[1] = 'b';
letters[2] = 'c';
Array Initialization
• Similarly:
is shorthand for:
• The assignment operator (=) can be used with array references, but such
use can lead to some unexpected results and subtle bugs:
int [] a = {5,4,3,2,1};
int [] b = new int[5]; // initialized to 0’s
b = a;
a[0] = 100;
System.out.println(“ a[0] is ” + a[0]+ “ and b[0] is ” +b[0]);
• Output:
• a and b are both references, i.e., a and b each holds a single address.
The = Operator
Int[] a = {5,4,3,2,1}
Int[] b = new int[5]
The = Operator
b=a
B[0] = 100;
• The == operator does not compare the contents of the arrays; the ==
operator compares references.
• int[] a = {5,4,3,2,1};
• int[] b = {5,4,3,2,1};
• int[] c = a;
• a == c evaluates to true.
• changeMe(...) assigns new values (200 and 400) to data[0] and data[1] and consequently
to x[0] and x[1]
Write a method:
• an array reference x
• two array indices i and j
In main:
int [] a = { 1,3,5,7,9};
swap(a, 2,4) // swap a[2] and a[4]
Before: 1 3 5 7 9
After: 1 3 9 7 5
Insertion Sort
[2 3 5 9 4]
• The last element must be inserted into the sorted group at its correct position. To place
this number (4) into its proper position:
• Copy the value in the last position (4) to a temporary variable, temp, so that the value is “safe.” That is, the value is
put aside for safe keeping.
• Compare 4 to 9, the element in the last position of the sorted sub-array. Since 9 is larger, 4 precedes 9 in the
sorted array; so shift (copy) 9 one position to the right :
• Compare 4 to 5. Since 5 is the larger number, shift 5 one position to the right:
[2 3 5 9 9] [2 3 5 5 9]
• Compare 4 to 3. Since 3 is less than 4, the correct position of 4 has been found. Now, place 4, which has been
saved in temp, in the position immediately following 3 and stop. The value 4 now sits in its correct place following 3
and preceding 5:
[2 3 5 5 9] [2 3 4 5 9]
Insertion Sort
that places the ith value of x into its proper position among the sorted values
x[0], x[1],…x[i-1], shifting numbers to the right if necessary.
• It incrementally builds sorted sub-arrays (x[0] x[1]), then (x[0] x[1] x[2]), then
(x[0] x[1] x[2] x[3])…and finally (x[0] x[1] x[2] x[3]…x[n-1]).
• A search routine that performs much better than linear search is binary search.
• To search an array x, for key, binary search first compares key to the item
situated in the middle of the array, say x[mid].
• If key < x[mid], then x[mid] and all elements greater than x[mid] are eliminated
from the search.
• If key > x[mid], then x[mid] and all items less than x[mid] can be eliminated.
• Thus after examining a single location, half of the data in the array can be
eliminated from the search.
• Binary search repeats this process on the part of the array that has not yet been
eliminated until the key is located or there are no more items to examine.
Binary Search
[3 5 6 9 11 23 25 26 27 29 33 35 36 37 39 42 45 46 48 58 62 67 70].
Since 27 is greater than the middle element (23), binary search now
searches those values greater than 23.
1% 2% 3% 4% 5% 6%
10 years 1.10 1.22 1.34 1.48 1.63 1.79
15 years 1.16 1.35 1.56 1.80 2.08 2.40
20 years 1.22 1.49 1.81 2.19 2.65 3.21
25 years 1.28 1.64 2.09 2.67 3.39 4.29
30 years 1.35 1.81 2.43 3.24 4.32 5.74
• Each storage cell in the table is uniquely identified by its row and
by its column. The rows and columns of a two-dimensional array
are indexed starting at 0.
Two-Dimensional Arrays
An array of arrays
It is easier to visualize a two-dimensional array as a simple table or grid
0 0 0 0
0 1 2 3
0 2 4 6
int[][][] threeD;
threeD new int[3][4][5];
for (int i = 0; i < 3; i++)
for (int j = 0; j < 4; j++)
for (int k = 0; k < 5; k++)
threeD[i][j][k] = i*j*k;
Processing a Two-Dimensional Array
Example:
• A contingency table is a two-dimensional grid often used as an aid for analyzing the
relationship between two variables.
Rock Heavy Metal Folk Jazz R& B Pop Country Other Total
Males 123 145 33 34 16 71 18 42 482
Females 138 112 50 27 93 75 10 13 518
Total 261 257 83 61 109 146 28 55 1000
• The numbers in the last column and last row are not part of the collected data.
• The number in the bottom right corner is the grand total, the sum of all data.
Processing a Two-Dimensional Array
Problem Statement:
• Write an application that queries a user for the number of rows and columns of a
contingency table, reads the data, row by row, and displays the data in tabular
form along with the row totals, column totals, and grand total.
1, 3, 6, 7, 9, and 8,
the program displays these 6 numbers together with the appropriate totals as:
1 3 6 | 10
7 9 8 | 24
8 12 14 | 34
10 and 24 are row totals, 8, 12, and 14 the column totals, and 34 the grand total.
• The “|” character is used to separate the data from the row totals.
Processing a Two-Dimensional Array
• display(...) prints the table along with the row, column, and
grand totals.
import java.util.*;
16. public static void display(int table[][], int numRows, int numCols,
int[] rowSums, int[] colSums)
17. {
18. // displays the contingency table
19. // displays row and column totals and grand total
20. System.out.println();
21. System.out.println();
22. System.out.println("Data including row and column totals: ");
23. System.out.println();
24. // print the table row by row
25. // after printing a row, print the row total
26. for(int row = 0; row < numRows; row++) // for each row
27. {
28. for (int col = 0; col < numCols; col++) // for each column
29. System.out.print(" "+table[row][col]+"\t");
30.
31. System.out.println("| "+rowSums[row]); // print the row total
32. }
display
33. System.out.println();
34. int grandTotal = 0;
35. // calculate the grand total from the column sums
36. // print the column sums then the grand total
37. for (int col = 0; col < numCols; col++) // for each column
38. {
39. grandTotal += colSums[col]; //add column sum to grandTotal
40. System.out.print(" "+colSums[col]+"\t"); //print column sum
41. }
42. System.out.println("| "+grandTotal);
43. }
getTotals
Number of rows: 2
Number of columns: 8
Enter data, row by row:
123 145 33 34 16 71 18 42 138 112 50 27 93 75 10 13
• The nested loop on lines 11-13 iterates through the table row by
row.
• If the table has 2 rows and 3 columns, the nested loop runs
through the indices of the array in the following order:
• The nested loop on lines 25-30 iterates through the table row
by row. Before incrementing the loop counter row the
method prints a separator character (‘|’) followed by the row
total. The data of each row is printed, followed by the
separator, followed by the row total. If the table consists of
two rows and three columns, printing proceeds:
• adds each column sum to the grand total ( line 37), and
• prints each column sum (line 38).
and not