0% found this document useful (0 votes)
22 views75 pages

9 2D Arrays One

assignment for coding class

Uploaded by

captainrickyoso
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views75 pages

9 2D Arrays One

assignment for coding class

Uploaded by

captainrickyoso
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

Multi-Dimensional Arrays

Reading: Chapter 9

• Declaring and Instantiating 2-D Arrays

• Aggregate Two-dimensional Array Operations.

• Other Multi-dimensional Arrays.

CSc 127A — Introduction to Computer Science I 1 Chapter 9 — Two-Dimensional Arrays


Two-Dimensional Arrays:

• An array that organizes data into rows and columns.

• Example:

• Grades for a course:

• Each row represents one student.

• Each column represents one assignment/exam/homework/etc:

Hw1 Hw2 Hw3 Exam Exam Average

Dave 98.0 95.0 87.5 92.5 83.0 91.2

Mary 100.0 97.5 92.0 95.5 98.5 96.7

Pete 99.0 85.0 87.5 82.5 89.0 88.6

CSc 127A — Introduction to Computer Science I 2 Chapter 9 — Two-Dimensional Arrays


Declaring and Instantiating 2-D Arrays:
Reading: Section 9.1.

• Creating an array requires two steps (for both 1-D and 2-D arrays):
1. Declaring the reference to the array
2. Instantiating the array.

• To declare a reference to a 2-D array:


datatype [][] arrayName;

• To instantiate an array:
arrayName = new datatype[ rowSize ] [ colSize ];

• rowSize is an int and is the number • colSize is an int and is the number
of rows that will be in the array. of columns that will be in the array.

CSc 127A — Introduction to Computer Science I 3 Chapter 9 — Two-Dimensional Arrays


Declaring and Instantiating 2-D Arrays (continued):

• Examples:

• Declaring and instantiating 2-D arrays of primitive types:


double [][] grades; // elements are doubles representing grades
grades = new double[ 200 ][ 10 ]; // 200 rows and 10 columns: 200 students, 10 grades each

• Declaring and instantiating 2-D arrays of objects:


String [][] studentNames; // each element is the name of a student
studentNames = new String[25][8]; // 25 rows, 8 columns: 1 column per section

String [][] monthlySchedule; // each element is one daily activity


monthlySchedule = new String[6][7]; // 6 rows, one row for each week

CSc 127A — Introduction to Computer Science I 4 Chapter 9 — Two-Dimensional Arrays


Declaring and Instantiating 2-D Arrays (continued):

• The declaration and instantiation can be done in the same step.


// 200 rows and 10 columns: 200 students, 10 grades each
double [][] grades = new double[ 200 ][ 10 ];

// each element is the name of a student, 1 column per section


String [][] studentNames = new String[25][8];

// each element represents one day in the month


String [][] monthlySchedule = new String[6][7];

CSc 127A — Introduction to Computer Science I 5 Chapter 9 — Two-Dimensional Arrays


Declaring and Instantiating 2-D Arrays (continued):

• When an array is instantiated, the elements are assigned default values as follows:

Array data type Default value

byte, short, int, long 0

float, double 0.0

char nul char

boolean false

Any object reference (for


null
example, a String)

CSc 127A — Introduction to Computer Science I 6 Chapter 9 — Two-Dimensional Arrays


Declaring and Instantiating 2-D Arrays (continued):

• The declaration of an array creates an area of memory that holds the elements of the array.

• This area of memory has one name, the name of the array.
double [][] zapNums = new double [3][5];

zapNums
0.0 0.0 0.0 0.0 0.0

0.0 0.0 0.0 0.0 0.0

0.0 0.0 0.0 0.0 0.0

• The declaration creates 3 arrays, each containing 5 doubles.

CSc 127A — Introduction to Computer Science I 7 Chapter 9 — Two-Dimensional Arrays


Accessing 2-D Array Elements:
Reading: Section 9.2.

• Can access individual elements of the array:

zapNums[0][2] = 7.5;
zapNums
0.0 0.0 0.0
-6.2
7.5 0.0 0.0 zapNums[1][0] = 42.0;

0.0
42.0 0.0 0.0 0.0 0.0
99.0
zapNums[1][4] = 99.0;
0.0 0.0 0.0 0.0
87.5 0.0
zapNums[2][3] = 87.5;

zapNums[0][2] = -6.2;

CSc 127A — Introduction to Computer Science I 8 Chapter 9 — Two-Dimensional Arrays


Accessing 2-D Array Elements (continued):

• Loops are the best way to print the contents of any array.

• For a 2-D array, you generally need two nested loops.

• Example:

zapNums
0.0 0.0 -6.2 0.0 0.0

42.0 0.0 0.0 0.0 99.0

0.0 0.0 0.0 87.5 0.0

for (int row = 0; row < 3; row++ ) { 0.0 0.0 -6.2 0.0 0.0

for (int col = 0; col < 5; col++ ) 42.0 0.0 0.0 0.0 99.0

System.out.print( zapNums[row][col] + " "); 0.0 0.0 0.0 87.5 0.0

System.out.println();
}

CSc 127A — Introduction to Computer Science I 9 Chapter 9 — Two-Dimensional Arrays


Accessing 2-D Array Elements (continued):

• The size of an array:

• It is best to have code that automatically knows how many rows and columns are present.

• With 1-D arrays, we did this as: arrayName.length

• For 2-D arrays, we need both the number of rows and the number of columns!

• For the number of rows, use: arrayName.length

• For the number of columns, first specify which row, then ask for the length: arrayName[2].length

CSc 127A — Introduction to Computer Science I 10 Chapter 9 — Two-Dimensional Arrays


Accessing 2-D Array Elements (continued):

• The printing example then becomes:

zapNums
0.0 0.0 -6.2 0.0 0.0

42.0 0.0 0.0 0.0 99.0

0.0 0.0 0.0 87.5 0.0


Tells us how many rows in the array.

Tells us how many columns


for (int row = 0; row < zapNums.length; row++ ) { in the current row.
for (int col = 0; col < zapNums[row].length; col++ )
System.out.print( zapNums[row][col] + " ");
System.out.println();
}

0.0 0.0 -6.2 0.0 0.0


42.0 0.0 0.0 0.0 99.0
0.0 0.0 0.0 87.5 0.0

CSc 127A — Introduction to Computer Science I 11 Chapter 9 — Two-Dimensional Arrays


Accessing 2-D Array Elements (continued):

• We can initialize values in a 2-D array by specifying a list of initial values.

• Example:
• A comma separates rows.
double [][] grades = { { 91.0, 92, 93, 99.0, 85.5 },
{ 87.5, 100, 92.5, 75.0, 62.0 }, • No comma after last row.
{ 90, 69, 73, 82.5, 90.5 } };

• Each row gets its


own set of { }’s.

Neatness counts!
Line things up when you enter the values.
• Outer set of { }’s define the
beginning and the end of the
array’s values.

CSc 127A — Introduction to Computer Science I 12 Chapter 9 — Two-Dimensional Arrays


Aggregate Operations on 2-D Arrays:
Computing averages:

• Want to compute the average for each row. For a grade book, the average is usually stored as the last column:
double [][] grades = { { 91.0, 92, 93, 99.0, 85.5, 0 },
{ 87.5, 100, 92.5, 75.0, 62.0, 0 },
{ 90, 69, 73, 82.5, 90.5, 0 } };

• To print the grades without the average column:


System.out.println("The grades without the averages:");

for ( row = 0; row < grades.length; row++ ) {

for ( col = 0; col < grades[row].length - 1; col++)


System.out.print( grades[row][col] + " ");

System.out.println();
}

CSc 127A — Introduction to Computer Science I 13 Chapter 9 — Two-Dimensional Arrays


Aggregate Operations on 2-D Arrays (continued):
Computing averages (continued):

• Nested loops to compute the average.

• The outer loop takes us through each row:


for ( row = 0; row < grades.length; row++ )

• The inner loop computes the sum of the grades for one row:
for ( col = 0; col < grades[row].length - 1; col++)

• To compute the average, we need to divide by the number of grades.

• How many grades are there?

• grades[row].length - 1

CSc 127A — Introduction to Computer Science I 14 Chapter 9 — Two-Dimensional Arrays


Aggregate Operations on 2-D Arrays (continued):
Computing averages (continued):
public class Grades3
{
public static void main(String[] args)
{
double [][] grades = { { 91.0, 92, 93, 99.0, 85.5, 0 },
{ 87.5, 100, 92.5, 75.0, 62.0, 0 },
{ 90, 69, 73, 82.5, 90.5, 0 } };
int row, col;

// Last column is for the average. Here's how to print


// grades without printing the average column.

System.out.println("The grades without the averages:");

for ( row = 0; row < grades.length; row++ ) {

for ( col = 0; col < grades[row].length - 1; col++)


System.out.print( grades[row][col] + " ");

System.out.println();
}

System.out.println(); // print a blank line

CSc 127A — Introduction to Computer Science I 15 Chapter 9 — Two-Dimensional Arrays


Aggregate Operations on 2-D Arrays (continued):
Computing averages (continued):
// Compute the average:
double sum;
for ( row = 0; row < grades.length; row++ ) {
sum = 0.0;
for ( col = 0; col < grades[row].length - 1; col++)
sum = sum + grades[row][col];

grades[row][grades[row].length - 1] = sum / (grades[row].length - 1);


}

// Print grades again with the average


System.out.println("The grades and the averages:");

for ( row = 0; row < grades.length; row++ ) {

for ( col = 0; col < grades[row].length; col++)


System.out.print( grades[row][col] + " ");

System.out.println();
}

} // end of method main


} // end of class Grades3

CSc 127A — Introduction to Computer Science I 16 Chapter 9 — Two-Dimensional Arrays


Accessing 2-D Array Elements (continued):

• Another way to initialize an array: Have the user type in the values.

• Want to enter grades into the array.

• Want to print the grades.


import java.util.Scanner;

public class Grades1


{
public static void main(String[] args)
{
Scanner inputScan = new Scanner( System.in );

double [][] grades = new double [3][5];


int row, col;

for ( row = 0; row < grades.length; row++ )

for ( col = 0; col < grades[row].length; col++) {


System.out.print("Enter a grade for row " + row + ": ");
grades[row][col] = inputScan.nextDouble();
}

System.out.println(); // print a blank line

CSc 127A — Introduction to Computer Science I 17 Chapter 9 — Two-Dimensional Arrays


Accessing 2-D Array Elements (continued):

• Another example: (continued)


System.out.println("The grades are:");

for ( row = 0; row < grades.length; row++ ) {

for ( col = 0; col < grades[row].length; col++)


System.out.print( grades[row][col] + " ");

System.out.println();
}

} // end of method main


} // end of class Grades1

CSc 127A — Introduction to Computer Science I 18 Chapter 9 — Two-Dimensional Arrays


Aggregate Operations on 2-D Arrays (continued): double [][] grades =
Computing average for each column: { { 91.0, 92, 93, 99.0, 85.5},
{ 87.5, 100, 92.5, 75.0, 62.0},
• Nested loops to compute the average. But, this time: { 90, 69, 73, 82.5, 90.5} };

• The outer loop takes us through each column:


for ( col = 0; col < grades[0].length; col++ )

• The inner loop computes the sum of the grades for one column:
for ( row = 0; row < grades.length; row++)

• To compute the average, we need to divide by the number of grades.

• How many grades are there?

CSc 127A — Introduction to Computer Science I 19 Chapter 9 — Two-Dimensional Arrays


Aggregate Operations on 2-D Arrays (continued):
Computing average for each column (continued):
public class Grades4
{
public static void main(String[] args)
{
double [][] grades = { { 91.0, 92, 93, 99.0, 85.5},
{ 87.5, 100, 92.5, 75.0, 62.0},
{ 90, 69, 73, 82.5, 90.5} };
int row, col;

System.out.println("The grades:");

for ( row = 0; row < grades.length; row++ ) {

for ( col = 0; col < grades[row].length; col++)


System.out.print( grades[row][col] + " ");

System.out.println();
}

System.out.println(); // print a blank line

CSc 127A — Introduction to Computer Science I 20 Chapter 9 — Two-Dimensional Arrays


Aggregate Operations on 2-D Arrays (continued):
Computing average for each column (continued):
// Compute the average for each column
double sum;

for ( col = 0; col < grades[0].length; col++ ) {


sum = 0.0;
for ( row = 0; row < grades.length; row++)
sum = sum + grades[row][col];

System.out.print("Average for column " + col + " is ");

System.out.println(sum / grades.length);
}

} // end of method main


} // end of class Grades4

CSc 127A — Introduction to Computer Science I 21 Chapter 9 — Two-Dimensional Arrays


Aggregate Operations on 2-D Arrays (continued):
Uneven rows:

• Consider the following declaration:


double [][] grades = { { 91.0, 92, 93, 85.5 },
{ 87.5, 100, 92.5 },
{ 90, 69, 73, 82.5, 90.5 } };

• This does compile(!!)

• It is not a requirement that each row have the same length.

grades
91 92 93 85.5

87.5 100 92.5

90 69 73 82.5 90.5

CSc 127A — Introduction to Computer Science I 22 Chapter 9 — Two-Dimensional Arrays


Aggregate Operations on 2-D Arrays (continued):
Uneven rows:

• Consider the following declaration:


double [][] grades = { { 91.0, 92, 93, 85.5 },
{ 87.5, 100, 92.5 },
{ 90, 69, 73, 82.5, 90.5 } };

• How to print the elements of the array?

• Use the length of each row to terminate the inner-loop:


for ( row = 0; row < grades.length; row++ ) {

for ( col = 0; col < grades[row].length; col++)


System.out.print( grades[row][col] + " ");

System.out.println();
}

CSc 127A — Introduction to Computer Science I 23 Chapter 9 — Two-Dimensional Arrays


Aggregate Operations on 2-D Arrays (continued):
Uneven rows (continued):

• How to compute the average from each column?


double [][] grades = { { 91.0, 92, 93, 85.5 },
{ 87.5, 100, 92.5 },
{ 90, 69, 73, 82.5, 90.5 } };

• Use the length of each row to check:


for ( col = 0; col < ________________________________; col++ ) {
sum = 0.0;
count = 0;

for ( row = 0; row < __________________________; row++ ) {


if ( _______________________________________ ) {
sum = sum + grades[row][col];
count++;
}
}

average = sum / count;


System.out.println("Average for column " + col + " = " + average);
}

CSc 127A — Introduction to Computer Science I 24 Chapter 9 — Two-Dimensional Arrays


Aggregate Operations on 2-D Arrays (continued):

• Uneven rows example code:


public class Grades5
{
public static void main(String[] args)
{
double [][] grades = { { 91.0, 92, 93, 85.5 },
{ 87.5, 100, 92.5 },
{ 90, 69, 73, 82.5, 90.5 } };
int row, col;

System.out.println("The grades are:");

for ( row = 0; row < grades.length; row++ ) {

for ( col = 0; col < grades[row].length; col++)


System.out.print( grades[row][col] + " ");

System.out.println();
}

System.out.println();

CSc 127A — Introduction to Computer Science I 25 Chapter 9 — Two-Dimensional Arrays


Aggregate Operations on 2-D Arrays (continued):

• Uneven rows example code (continued):


double sum;
int count;
double average;
for ( col = 0; col < 5; col++ ) {
sum = 0.0;
count = 0;
for ( row = 0; row < grades.length; row++ )
if ( col < grades[row].length ) {
sum = sum + grades[row][col];
count++;
}
average = sum / count;
System.out.println("Average for column " + col + " = " + average);
}

} // end of method main


} // end of class Grades5

CSc 127A — Introduction to Computer Science I 26 Chapter 9 — Two-Dimensional Arrays


Aggregate Operations on 2-D Arrays (continued):
Uneven rows (continued):

• Consider a 2-D array of String’s:


private String [][] presidents = {
{ "Thomas", "Jefferson" },
{ "William", "Henry", "Harrison" },
{ "Abraham", "Lincoln" },
{ "Hiram", "Ulysses", "Simpson", "Grant" },
{ "Rutherford", "Birchard", "Hayes" },
{ "Calvin", "Coolidge" },
{ "George", "Herbert", "Walker", "Bush" },
{ "William", "(Bill)", "Jefferson", "Clinton" } };

• Write a method that returns a String containing the third name of each President:
public String thirdNames() {
String result = new String("");
int row;
for (row = 0; row < ______________________________; row++)

if ( ______________________________________________ )
result = result + presidents[row][2] + "\n";
return result;
}

CSc 127A — Introduction to Computer Science I 27 Chapter 9 — Two-Dimensional Arrays


Aggregate Operations on 2-D Arrays (continued):
Uneven rows (continued):

• Write a method that takes an int argument that specifies which name is wanted:
public String names(int position) {
String result = new String("");
int row;
for (row = 0; row < ______________________________; row++)

if ( ___________________________________________ )

result = result + presidents[row][___________________________] + "\n";


return result;
}

• Call this method by doing:


for (int i = 0; i < 4; i++) {
System.out.println("Names at position " + i + ":");
System.out.println(presNames.names(i));
System.out.println();
}

• What happens if position has a value larger than any of the names in the array?

CSc 127A — Introduction to Computer Science I 28 Chapter 9 — Two-Dimensional Arrays


Aggregate Operations on 2-D Arrays (continued):

• Uneven rows example code (continued):

• How to determine the largest number of columns without looking?

• Becomes a problem of finding the largest value.

• Each row “knows” how many columns it has.


// Find the row with the most columns

int mostColumns = _________________________; // assume first row has the most

// Check the rest of the rows for a row with more columns
for ( row = 1; row < grades.length; row++ )

if ( ___________________________________________________ )
mostColumns = grades[row].length;

CSc 127A — Introduction to Computer Science I 29 Chapter 9 — Two-Dimensional Arrays


Aggregate Operations on 2-D Arrays (continued):

• How to determine the largest number of columns without looking?


public class Grades6
{
public static void main(String[] args)
{
double [][] grades = { { 91.0, 92, 93, 85.5 },
{ 87.5, 100, 92.5 },
{ 90, 69, 73, 82.5, 90.5 },
{ 82, 19, 100, 67.5, 98.5, 93.5 },
{ 75, 76, 72, 83.5} };
int row, col;
double sum;
int count;
double average;

// Find the row with the most columns


int mostColumns = grades[0].length; // assume first row has the most

// Check the rest of the rows for a row with more columns
for ( row = 1; row < grades.length; row++ )
if ( mostColumns < grades[row].length )
mostColumns = grades[row].length;

CSc 127A — Introduction to Computer Science I 30 Chapter 9 — Two-Dimensional Arrays


Aggregate Operations on 2-D Arrays (continued):

• How to determine the largest number of columns without looking?


// Compute and print average for each column
for ( col = 0; col < mostColumns; col++ ) {
sum = 0.0;
count = 0;
for ( row = 0; row < grades.length; row++ )
if ( col < grades[row].length ) {
sum = sum + grades[row][col];
count++;
}
average = sum / count;
System.out.println("Average for column " + col + " = " + average);
}

} // end of method main


} // end of class Grades6

CSc 127A — Introduction to Computer Science I 31 Chapter 9 — Two-Dimensional Arrays


static Variables and Methods:
Reading: Section 7.11, pages 408-411.
• static Variables:

• Also known as “class variables”.

• One copy of a static variable is created per class.


• static variables are not associated with any of the objects of that class, only with the class.

• Every object shares (can access) a static variable.


• static constants are often declared as public.

• Math.PI and Math.E are examples.

• Syntax:
accessSpecifier static dataType variableName;

• Examples:
public static int countAutos = 0;
private static short processID = 2;

CSc 127A — Introduction to Computer Science I 32 Chapter 9 — Two-Dimensional Arrays


static Variables and Methods (continued):
• static Methods:

• Also known as “class methods”.

• Often defined to access and change static variables.

• static methods cannot access instance variables:


• static methods are associated with the class, not with any object.
• static methods do not have access to the implicit parameter this.
• static methods can be called without first creating an instance of a class.

• The methods in the Math class are all declared static.

• Allows use of Math.min(), Math.abs(), etc., without first having to create an instance of Math.

• The function main is declared static so it can be called by the Java Virtual Machine without creating an
instance of the class that contains main.

String name = new String("Patrick");

Math yoke = new Math(...); // do not do this!!!

double x = Math.sqrt(1274.873);

CSc 127A — Introduction to Computer Science I 33 Chapter 9 — Two-Dimensional Arrays


static Variables and Methods (continued):

• Rules for static and non-static methods.

static Non-static
Method Method

Access instance variables? No Yes

Access static class variables? Yes Yes

Call static class methods? Yes Yes

Call non-static instance methods? No Yes

Use the object reference this? No Yes

CSc 127A — Introduction to Computer Science I 34 Chapter 9 — Two-Dimensional Arrays


static Variables and Methods (continued):

• An example that maintains a class variable and provides a wrap-around increment method.
public class ProcessID public ProcessID(){
{ // Get id for this object:
private static short pid = 2; myId = nextPid();
// Instance variables here... // rest of constructor here...
private short myId; } // end of constructor

public static short nextPid() } // end of class ProcessID


{
short temp;
temp = pid;
if ( pid == 32767 ) public class Zap {
pid = 2;
else public static void main(String [] args)
pid += 1; {
short anotherID = ProcessID.nextPid();
return temp; }
} // end of method nextPid }

public static short currentPid()


{
return pid;
} // end of method currentPid

CSc 127A — Introduction to Computer Science I 35 Chapter 9 — Two-Dimensional Arrays


Sequential Search:
Reading: Section 8.6.1, pages 505 - 509.

• A Sequential Search can be used to determine if a specific value (the search key) is in an array.

• Approach:

• Start with the first element and compare each element to the search key:

• If found, return the index of the element that contains the search key.

• If not found, return -1.

• Because -1 is never a valid index for an array.

CSc 127A — Introduction to Computer Science I 36 Chapter 9 — Two-Dimensional Arrays


Sequential Search (continued):

• Example: A class that stores random integers in an array. Want to ask if a particular number is present in the
array.

• Constructor puts random integers in the array.

• The findNumber method looks for the value.


import java.util.Random; public int findNumber(int key)
{
public class Search1 for ( int i = 0; i < numbers.length; i++ )
{ if ( numbers[i] == key )
private int [] numbers; return i;

public Search1(int randomSeed) return -1;


{ } // end of method findNumber
Random more = new Random(randomSeed);
public String toString()
numbers = new int[16]; {
int i; int i;
for (i = 0; i < numbers.length; i++) String temp = new String("");
numbers[i] = more.nextInt(20) - 5;
} // end of constructor for ( i = 0; i < numbers.length; i++ )
temp = temp + " " + numbers[i];

return temp;
} // end of method toString
} // end of class Search1

CSc 127A — Introduction to Computer Science I 37 Chapter 9 — Two-Dimensional Arrays


Sequential Search (continued):

• Example: findNumber continued:


public class Search1Client
{
public static void main( String [] args )
{
Search1 first, second;
int i, result;

first = new Search1(42);


second = new Search1(43);

System.out.println("first contains:");
System.out.println(first.toString());

System.out.println("second contains:");
System.out.println(second.toString());
System.out.println();

CSc 127A — Introduction to Computer Science I 38 Chapter 9 — Two-Dimensional Arrays


Sequential Search (continued):

• Example: findNumber continued:


System.out.println("Searching in first:");
for ( i = -3; i < 7; i++ ) {
result = first.findNumber(i);
if ( result != -1 )
System.out.println(i + " found at position " + result);
else
System.out.println("Did not find " + i);
}
System.out.println();

System.out.println("Searching in second:");
for ( i = -3; i < 7; i++ ) {
result = second.findNumber(i);
if ( result != -1 )
System.out.println(i + " found at position " + result);
else
System.out.println("Did not find " + i);
}

} // end of method main

} // end of class Search1Client

CSc 127A — Introduction to Computer Science I 39 Chapter 9 — Two-Dimensional Arrays


Sequential Search (continued):
Reading: Section 8.6.5, pages 526-527.

• What if the values in the array are already sorted?

• If the search key is not in the array, we can detect that condition when we find a value that is higher than the
search key.

• All elements past that position will also be greater than the search key.

• The loop can stop as soon as

• The number is found, OR

• A larger number is found.


public int findNumber(int key) {
for ( int i = 0; numbers[i] <= key && i < numbers.length; i++ )
if ( numbers[i] == key )
return i;

return -1;
} // end of method findNumber

CSc 127A — Introduction to Computer Science I 40 Chapter 9 — Two-Dimensional Arrays


Sequential Search (continued):

• There is an error on the previous slide(!!)


• numbers[i] <= key will generate a subscript out-of-bounds error when i == numbers.length

• Solution: check i < numbers.length first; i.e.,


public int findNumber(int key) {

for ( int i = 0; i < numbers.length && numbers[i] <= key; i++ )


if ( numbers[i] == key )
return i;

return -1;
} // end of method findNumber

• Java uses short-circuit evaluation.

• For &&, when the first expression (on the left) is false, the second expression (on the right) is not
evaluated.

• For ||, when the first expression is true, the second expression is not evaluated.

CSc 127A — Introduction to Computer Science I 41 Chapter 9 — Two-Dimensional Arrays


Binary Search:
Reading: Section 8.6.6, pages 527 - 532.

• Binary Search is like “Guess a Number”:

• To guess a number between 1 and 100, start with 50 (the halfway point):

• If the answer is that the number is greater than our guess, we know to guess in the upper-half.

• If the answer is that the number is less than our guess, we know to guess in the lower-half.

• Keep guessing that the number is in the middle of the remaining numbers:

• We eliminate half the remaining numbers with each guess.

• How many guesses does it take (at most) to find a number between 1 and 100?

• This approach works because the values 1-100 are a “sorted” list of numbers.

• To use Binary Search on an array of items, they have to be sorted.

CSc 127A — Introduction to Computer Science I 42 Chapter 9 — Two-Dimensional Arrays


Binary Search (continued):

• The Algorithm:

• Compare the middle element of the array with the search key.

• If they are equal,

• Found the value! Return the index of this middle element.

• If the middle element’s value is > the search key,

• Continue search in the left (lower) half of the array.

• If the middle element’s value is < the search key,

• Continue search in the right (upper) half of the array.

• The sub-array we search each time keeps shrinking in size.

• It is cut (about) in half at every iteration.

• What if the search key is not in the array?

• The sub-array that we search will eventually become empty.

• At that point, we return -1.

CSc 127A — Introduction to Computer Science I 43 Chapter 9 — Two-Dimensional Arrays


Binary Search (continued):

• The Algorithm:

• Compare the middle element of the array with the search key.

• If they are equal, we found the search key. Return the index of this middle element.

• If the middle element’s value is > the search key, continue search in the left (lower) half of the array.

• If the middle element’s value is < the search key, continue search in the right (upper) half of the array.

• Consider a small array of 7 elements. Assume the search key is -4.

• First step:
start middle end
0 3 6

0 1 2 3 4 5 6
numbers -42 -12 -4 19 21 53 62

CSc 127A — Introduction to Computer Science I 44 Chapter 9 — Two-Dimensional Arrays


Binary Search (continued):

• Consider a small array of 7 elements. Assume the search key is -4.

• Second step:
start middle end
0 1 2

0 1 2 3 4 5 6
numbers -42 -12 -4 19 21 53 62

• Third step:

• We found it! start


2
middle
2
end
2

0 1 2 3 4 5 6
numbers -42 -12 -4 19 21 53 62

CSc 127A — Introduction to Computer Science I 45 Chapter 9 — Two-Dimensional Arrays


Binary Search (continued):

• Consider a small array of 7 elements. Assume the search key is -5.

• First step: • Second step:


start middle end start middle end
0 3 6 0 1 2

0 1 2 3 4 5 6 0 1 2 3 4 5 6
numbers -42 -12 -4 19 21 53 62 numbers -42 -12 -4 19 21 53 62

• Third step: • Fourth step:


start middle end start middle end
2 2 2 2 2 1

0 1 2 3 4 5 6 0 1 2 3 4 5 6
numbers -42 -12 -4 19 21 53 62 numbers -42 -12 -4 19 21 53 62
start > end; value not in the array

CSc 127A — Introduction to Computer Science I 46 Chapter 9 — Two-Dimensional Arrays


Binary Search (continued):

• Consider an somewhat larger array of 15 elements. Assume the search key is 81.

• First step:
start middle end
0 7 14

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
numbers -42 -12 -4 19 21 53 62 65 73 78 82 83 89 97 98

• Second step:
start middle end
8 11 14

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
numbers -42 -12 -4 19 21 53 62 65 73 78 82 83 89 97 98

CSc 127A — Introduction to Computer Science I 47 Chapter 9 — Two-Dimensional Arrays


Binary Search (continued):

• Consider an somewhat larger array of 15 elements. Assume the search key is 81.

• Third step:
start middle end
8 9 10

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
numbers -42 -12 -4 19 21 53 62 65 73 78 82 83 89 97 98

• Fourth step:
start middle end
9 9 9

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
numbers -42 -12 -4 19 21 53 62 65 73 78 82 83 89 97 98

CSc 127A — Introduction to Computer Science I 48 Chapter 9 — Two-Dimensional Arrays


Binary Search (continued):

• Consider an somewhat larger array of 15 elements. Assume the search key is 81.

• Fifth step:
start middle end
10 9 9

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
numbers -42 -12 -4 19 21 53 62 65 73 78 82 83 89 97 98

int middle, start = 0, end = ??;


while ( end >= start ) {

CSc 127A — Introduction to Computer Science I 49 Chapter 9 — Two-Dimensional Arrays


Selection Sort:
Reading: Section 8.6.2, pages 510 - 515.

• Selection Sort works by:

• Finding the largest element in the array.

• Placing it at the end of the array.

• Finding next-largest element in the array.

• Placing it at the next-to-last position in the array.

• Etc.

• Think of the array as having two sections:

• Those elements on the left that are not (yet) in order — the unsorted sub-array.

• Those elements on the right that are in order — the sorted sub-array.

CSc 127A — Introduction to Computer Science I 50 Chapter 9 — Two-Dimensional Arrays


Selection Sort (continued):

• An example with 15 elements:

• Find the location of the largest number in the array:

maxLocation 6
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
numbers 78 97 62 73 89 65 98 21 19 -42 83 82 53 -4 -12

• Result after the swap of the numbers in location 6 and the last element in the array:

maxLocation 6
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
numbers 78 97 62 73 89 65 -12 21 19 -42 83 82 53 -4 98

unsorted sorted

CSc 127A — Introduction to Computer Science I 51 Chapter 9 — Two-Dimensional Arrays


Selection Sort (continued):

• An example with 15 elements:

• Find the location of the largest number in the unsorted portion of the array:

maxLocation 1
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
numbers 78 97 62 73 89 65 -12 21 19 -42 83 82 53 -4 98

unsorted sorted

• Result after the swap of the numbers in location 1 and the next-to-last element in the array:

maxLocation 1
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
numbers 78 -4 62 73 89 65 -12 21 19 -42 83 82 53 97 98

unsorted sorted

CSc 127A — Introduction to Computer Science I 52 Chapter 9 — Two-Dimensional Arrays


Selection Sort (continued):

• An example with 15 elements:

• Find the location of the largest number in the unsorted portion of the array:

maxLocation 4
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
numbers 78 -4 62 73 89 65 -12 21 19 -42 83 82 53 97 98

unsorted sorted

• Result after the swap of the numbers in location 4 and the last element in the unsorted array:

maxLocation 4
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
numbers 78 -4 62 73 53 65 -12 21 19 -42 83 82 89 97 98

unsorted sorted

CSc 127A — Introduction to Computer Science I 53 Chapter 9 — Two-Dimensional Arrays


Selection Sort (continued):

• Find the index of the largest element. (We’ve done this before!)
private static int indexOfLargestElement( int [] values, int size )
{
int index = 0;

for ( int i = 1; i <= size; i++ )


if ( values[i] > values[index] )
index = i;

return index;
} // end of method indexOfLargestElement

• The parameter size indicates the part of the array to search.

• The “unsorted portion” of the array will be those elements in positions 0 to size.

CSc 127A — Introduction to Computer Science I 54 Chapter 9 — Two-Dimensional Arrays


Selection Sort (continued):

• Need to swap two values.

• Note: the following does not work. Why?


maxLocation = indexOfLargestElement( numbers, i );

// swap the largest with the current position


numbers[maxLocation] = numbers[i];
numbers[i] = numbers[maxLocation];

CSc 127A — Introduction to Computer Science I 55 Chapter 9 — Two-Dimensional Arrays


Selection Sort (continued):

• Need to swap two values.

• Declare a “temporary variable” of the same type as the elements of the array.

• Use temp to temporarily hold one of the values being swapped.


maxLocation = indexOfLargestElement( numbers, i );

// swap the largest with the current position


temp = numbers[maxLocation];
numbers[maxLocation] = numbers[i];
numbers[i] = temp;

CSc 127A — Introduction to Computer Science I 56 Chapter 9 — Two-Dimensional Arrays


Selection Sort (continued):

• A class to sort an integer array.


public class Sorter {

public static void selectionSort( int [] numbers )


{
int temp; // temporary location for swap
int maxLocation; // index of maximum value in subarray

for (int i = numbers.length - 1; i > 0; i-- )


{
// find location of the largest in the subarray
maxLocation = indexOfLargestElement( numbers, i );

// swap the largest with the current position


temp = numbers[maxLocation];
numbers[maxLocation] = numbers[i];
numbers[i] = temp;
}
} // end of method selectionSort

CSc 127A — Introduction to Computer Science I 57 Chapter 9 — Two-Dimensional Arrays


Selection Sort (continued):

• A class to sort an integer array (continued):


// A private "helper" method to find the index of the largest
// value in the portion of the array from index 0 to index size.
private static int indexOfLargestElement( int [] values, int size )
{
int index = 0;

for ( int i = 1; i <= size; i++ )


if ( values[i] > values[index] )
index = i;

return index;
} // end of method indexOfLargestElement
} // end of Sorter

CSc 127A — Introduction to Computer Science I 58 Chapter 9 — Two-Dimensional Arrays


Selection Sort (continued):

• An example of how to use the Sorter class:


public class SelectionSortClient {

public static void main(String [] args)


{
int [] numbers = { 78, 97, -12, 73, 89, 65, 98, 53,
19, -42, 83, 82, 21, -4, 62};

System.out.println("The array before sorting:");


for ( int i = 0; i < numbers.length; i++)
System.out.print( numbers[i] + " " );
System.out.println("\n");

Sorter.selectionSort( numbers );

System.out.println("The array after sorting:");


for ( int i = 0; i < numbers.length; i++)
System.out.print( numbers[i] + " " );
System.out.println();

} // end of method main

} // end of class SelectionSortClient

CSc 127A — Introduction to Computer Science I 59 Chapter 9 — Two-Dimensional Arrays


Selection Sort (continued):

• Measuring sorting performance:

• Need a way to know the start and end times of the sort.

• The Date class:

• Create an instance of Date. It will record the time at which it was created.

• Create a second instance when done.

• Use the getTime() method.

• Returns a long that contains the time at which the Date instance was created.

• Measured in milliseconds since the Epoch, which is January 1, 1970.


import java.util.Date;
...
Date startTime, endTime;

startTime = new Date();

// Code here that you want to measure...

endTime = new Date();

long elapsedTime = endTime.getTime() - startTime.getTime();

CSc 127A — Introduction to Computer Science I 60 Chapter 9 — Two-Dimensional Arrays


Selection Sort (continued):
public static void selectionSort( int [] numbers )
{
int temp; // temporary location for swap
int maxLocation; // index of maximum value in subarray
Date startTime, endTime;
startTime = new Date();

for (int i = numbers.length - 1; i > 0; i-- )


{
// find location of the largest in the subarray
maxLocation = indexOfLargestElement( numbers, i );

// swap the largest with the current position


temp = numbers[maxLocation];
numbers[maxLocation] = numbers[i];
numbers[i] = temp;
}

endTime = new Date();

System.out.println("startTime: " + startTime.getTime());


System.out.println("endTime: " + endTime.getTime());

System.out.println("Execution time: " +


(endTime.getTime() - startTime.getTime()));
} // end of method selectionSort

CSc 127A — Introduction to Computer Science I 61 Chapter 9 — Two-Dimensional Arrays


Selection Sort (continued):

• Measuring sorting performance:

• Results of sorts using 3 different machines. Times are in seconds.

2.8 GHz lectura


numbers 2.0 GHz G-5 Mac dual quad-core
Core 2 Duo Mac
Nehalam processors

10,000 0.294 0.117 0.126

100,000 25.685 6.789 6.197

500,000 671.996 170.104 158.884

750,000 1,594.389 381.835 350.289

1,000,000 2,487.532 676.795 624.252

CSc 127A — Introduction to Computer Science I 62 Chapter 9 — Two-Dimensional Arrays


Selection Sort (continued):

• Measuring sorting performance:

• Sorting on MacBook Pro, 2.8 GHz Intel Core 2 Duo.


300
elements time (seconds)
50,000 2.250
100,000 6.789
225
150,000 15.406
200,000 27.283
250,000 42.550
150
300,000 61.177
350,000 83.232
400,000 108.860
450,000 139.053 75
500,000 170.104
550,000 204.501

0
50,000 200,000 350000 500000

CSc 127A — Introduction to Computer Science I 63 Chapter 9 — Two-Dimensional Arrays


Multi-dimensional Arrays:
Reading: Section 9.6, pages 606 - 608.

• Example: Want to keep track of sales on a per-year, per-week, and a per-day basis.

• Use a 3-dimensional array:

• First dimension: year What is the last day of the last year?
• Second dimension: week sales[9][51][6]

• Third dimension: day of the week What is the first day of 4th week of the last year?
• Sample code:
sales[9][3][0]

// declare a three-dimensional array


double [][][] sales;
// instantiate the array for 10 years, 52 weeks, and 7 days
sales = new double [10][52][7]; //
// set the value of the first element (first day we are open)
sales[0][0][0] = 2380.47;
sales[0][0][1] = 1963.52; // second day we are open
sales[1][0][0] = 2316.23; // first day of the second year
sales[1][3][6] = 2981.62; // 7th day of the 4th week of the 2nd year

CSc 127A — Introduction to Computer Science I 64 Chapter 9 — Two-Dimensional Arrays


Multi-dimensional Arrays (continued):

• General pattern for processing a three-dimensional array:


int i, j, k;

for ( i = 0; i < arrayName.length; i++ )

for ( j = 0; j < arrayName[i].length; j++ )

for ( k = 0; k < arrayName[i][j].length; k++ ) {

// do something with element [i][j][k]

CSc 127A — Introduction to Computer Science I 65 Chapter 9 — Two-Dimensional Arrays


Multi-dimensional Arrays (continued):

• More specific example for the sales problem.

• It is best to use descriptive names for the loop indices.

• Compute the total of all the sales.


int year, week, day;
double sum = 0.0;
for ( year = 0; year < sales.length; year++ )
for ( week = 0; week < sales[year].length; week++ )
for ( day = 0; day < sales[year][week].length; day++ ) {
sum = sum + sales[year][week][day];
}

CSc 127A — Introduction to Computer Science I 66 Chapter 9 — Two-Dimensional Arrays


Multi-dimensional Arrays (continued):

• Printing the sales figures:

• Want the sales for one week all on the same line.

• Want a blank line after every fourth week.


int year, week, day;
for ( year = 0; year < sales.length; year++ ) {
for ( week = 0; week < sales[year].length; week++ ) {
for ( day = 0; day < sales[year][week].length; day++ ) {
System.out.print( sales[year][week][day] + "\t");
} // loop for day
// finish line after each week
System.out.println();
// blank line after each set of 4 weeks
if ( ___(week + 1) % 4 == 0___ )
System.out.println();
} // loop for week
System.out.println("------------------------------------------------");
}
CSc 127A — Introduction to Computer Science I 67 Chapter 9 — Two-Dimensional Arrays
Multi-dimensional Arrays (continued):

• Suppose we want the sales total for just the 4th year?

• What changes?
int year, week, day;
double sum = 0.0;
// for ( year = 0; year < sales.length; year++ )
year = 3;
for ( week = 0; week < sales[year].length; week++ )
for ( day = 0; day < sales[year][week].length; day++ ) {
sum = sum + sales[year][week][day];
}

CSc 127A — Introduction to Computer Science I 68 Chapter 9 — Two-Dimensional Arrays


Multi-dimensional Arrays (continued):

• Suppose we want the sales total for all the sales in June (across all the years)?

• What changes?
int year, week, day;
double sum = 0.0;
for ( year = 0; year < sales.length; year++ )
for ( week = 21; week < 26; week++ )
for ( day = 0; day < sales[year][week].length; day++ ) {
sum = sum + sales[year][week][day];
}

CSc 127A — Introduction to Computer Science I 69 Chapter 9 — Two-Dimensional Arrays


Multi-dimensional Arrays (continued):

• There is no upper-bound on the number of dimensions an array can have in Java.

• Why would we need more than a three-dimensional array?

• For example, suppose we have seven stores?


// declare a four-dimensional array
double [][][][] sales;
// instantiate the array for 7 stores, 10 years, 52 weeks, and 7 days
sales = new double [7][10][52][7];
// set the value of the first element (first day we are open) for the 3rd store
sales[2][0][0][0] = 2380.47;

CSc 127A — Introduction to Computer Science I 70 Chapter 9 — Two-Dimensional Arrays


Multi-dimensional Arrays (continued):

• Sales figures for seven stores?

• Same basic idea, just need one more loop...


int store, year, week, day;
double sum = 0.0;
for ( store = 0; store < sales.length; store++ )
for ( year = 0; year < sales[store].length; year++ )
for ( week = 0; week < sales[store][year].length; week++ )
for ( day = 0; day < sales[store][year][week].length; day++ ) {
sum = sum + sales[store][year][week][day];
}

CSc 127A — Introduction to Computer Science I 71 Chapter 9 — Two-Dimensional Arrays


The ArrayList Class:
Reading: Section 9.7, pages 609 - 622.

• Arrays have a fixed size once they have been instantiated.

• What if we do not know how many elements we will need?

• Reading values from a file.

• Returning search results ("Find all people named Smith")

• Could create a very large array:

• And, hope it is large enough!

• Generally, would be a waste of memory space. (Do we care about that?)

• Could create a moderate size array:

• When it fills up, we create a larger array, and copy elements from the original to the larger array.

• How much larger should the new array be?

• Need a better idea...

CSc 127A — Introduction to Computer Science I 72 Chapter 9 — Two-Dimensional Arrays


The ArrayList Class (continued):

• An ArrayList stores elements in an array-like manner, and expands in size automatically.

• Is part of the java.util package; i.e., you need:


import java.util.ArrayList;

• All elements in an ArrayList are object references; i.e., String, Player, Chest, etc.

• The ArrayList class is a generic class.

• That is, it is written to store object references of any type the client desires.

CSc 127A — Introduction to Computer Science I 73 Chapter 9 — Two-Dimensional Arrays


The ArrayList Class (continued):

• Declaring an ArrayList:
ArrayList<String> aBunchOfNames;

• The type of object stored in the ArrayList is stated in between the < >'s

• There are two constructors for the ArrayList class:

• The default constructor will create 10 elements.


aBunchOfNames = new ArrayList<String>();

• The programmer can also state the desired number of initial items:
ArrayList<String> manyNames = new ArrayList<String>( 25 );

• An ArrayList has both a size and a capacity.


• aBunchOfNames has a capacity of 10.
• manyNames has a capacity of 25.

• Both start out with a size of 0, since no objects have been stored in either one.

CSc 127A — Introduction to Computer Science I 74 Chapter 9 — Two-Dimensional Arrays


The ArrayList Class (continued):

• Some of the methods available to ArrayList's:

Return Type Method name and argument list

add( E element)
boolean
appends element to the end of the list
clear( )
void
removes all the elements in the list
size( )
int
returns the number of elements in the list
remove( int index )
E
removes the element at the specified index position
get( int index )
E returns the element at the specified index position; the element is not removed
from the list
set( int index, E element )
E
replaces the element at the specified index position with the specified element
trimToSize( )
void
sets the capacity of the list to its current size

CSc 127A — Introduction to Computer Science I 75 Chapter 9 — Two-Dimensional Arrays

You might also like