0% found this document useful (0 votes)
21 views125 pages

Introduction To Java Programming Chapter 6: Single-Dimensional Arrays

Uploaded by

Dany Merhej
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)
21 views125 pages

Introduction To Java Programming Chapter 6: Single-Dimensional Arrays

Uploaded by

Dany Merhej
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/ 125

INTRODUCTION TO

JAVA PROGRAMMING
Chapter 6: Single-Dimensional Arrays 1
Introduction
• Often you will have to work with a large number of values
during the execution of a program. Suppose that you need
to read 100 numbers, compute their average, and find out
how many numbers are above the average.

• An efficient, organized approach is needed. Java and most


other high-level languages provide a data structure, the
array.

• An array stores a fixed-size sequential collection of


elements of the same type.

• A single array variable can reference a large collection of


data. 2
Opening Problem
• Read one hundred numbers, compute their average, and find out
how many numbers are above the average.

Run 3
Introducing Arrays
• An array is a collection of variables of the same type.

An array reference variable is


used to access the elements
in an array using an index

double[] numbers= new double[NUMBER_OF_ELEMENTS];

• Once an array is created, its size is fixed. 4


Introducing Arrays
Declaring “Array Variables”
• To use an array in a program, you must declare a variable to
reference the array and specify the array’s element type
elementType[] arrayRefVar;

• The elementType can be any data type, and all elements in the
array will have the same data type.

• For example, the following code declares a variable myList that


references an array of double elements.

double[] myList;

Note: You can also write


elementType arrayRefVar[]; //C language style
5
elementType[] arrayRefVar; // This style is however preferred
Introducing Arrays
Declaring “Array Variables”
• To use an array in a program, you must declare a variable to
reference the array and specify the array’s element type
elementType[] arrayRefVar;
• Unlike declarations for primitive data type variables, the declaration
of an array variable does not allocate any space in memory for the
array. It creates only a storage location for the reference to an array.
• If an array reference variable does not contain a reference to an
array, the value of the array reference variable is null.

6
Introducing Arrays
Creating Arrays
• After an array variable is declared, For exp:
elementType[] arrayRefVar; double[] myList;

you can create an array by using the new operator with the
following syntax:
arrayRefVar=new elementType[arraySize];
For exp:
myList=new double[NUMBER_OF_ELEMENTS];
The last statement does two things:
1. it creates an array using “new elementType[arraySize]”.
2. it assigns the reference of the newly created array to the reference
7
variable “ arrayRefVar”.
Introducing Arrays
• The operations: For exp:
1
1. Declaring an array variable, double[] myList; 2
3
2. creating an array, myList=new double[NUMBER_OF_ELEMENTS];

3. and assigning the reference of the array to the variable


can be combined in one statement as:
elementType[] arrayRefVar=new elementType[arraySize];
double[] myList=new double[NUMBER_OF_ELEMENTS];

or (C language style):
8
elementType arrayRefVar[]=new elementType[arraySize];
Introducing Arrays
For example:
double[] myList = new double[10];
1. declares an array variable myList,

2. creates an array of ten elements of double type,

3. and assigns its reference to myList.

9
Introducing Arrays
• To assign values to the elements, use the syntax:
arrayRefVar[index] = value;
• For ex., suppose we have: double[] myList= new double[10];
the following code initializes the array.
myList[0] = 5.6;
myList[1] = 4.5;
0
myList[2] = 3.3; 0
0
myList[3] = 13.2; 0
myList[4] = 4.0; 0
0
myList[5] = 34.33; 0
myList[6] = 34.0; 0
0
myList[7] = 45.45; 0
myList[8] = 99.993;
myList[9] = 11123; 10
Note: array vs. array reference variable
• An array variable that appears to hold an array actually
contains a reference to that array. 0
0
double[] myList= new double[10]; 0
0
0
0
0
0
0
0
• Strictly speaking, an array variable and an array are
different, but most of the time the distinction can be
ignored.
• For simplicity, we say:
- myList is an array,
- instead of stating that myList is a variable that contains a reference
11
to an array of ten double elements.
Introducing Arrays
• Array Size: When space for an array is allocated, the array
size must be given, specifying the number of elements
that can be stored in it.
0
0
0
0
0
0
0
0
0
0

• The size of an array cannot be changed after the array is


created.
• Size can be obtained using: arrayRefVar.length
double[] myList= new double[10];
myList.length is 10. 12
Introducing Arrays
• Default Values :

0
0
0
0
0
0
0
0
0
0

• When an array is created, its elements are assigned


– the default value of 0 for the numeric primitive data types,
– the default value \u0000 for char types,
– the default value false for boolean types. 13
Introducing Arrays
• Array Indexed Variables: The array elements are accessed
through the index. Array indices are 0 based; that is, they
range from 0 to arrayRefVar.length-1
• In the figure, myList holds ten double values, and the indices are
from 0 to 9.

Each element in the array is represented using the following syntax,


known as an indexed variable: arrayRefVar[index] 14
Introducing Arrays
• Array Indexed Variables: After an array is created, an
indexed variable can be used in the same way as a regular
variable.
0
0
0
0
0
0
0
0
0
0

• For example, the following code adds the values in myList[0] and
myList[1] to myList[2].
myList[2] = myList[0] + myList[1];

15
Introducing Arrays
• Array Indexed Variables: After an array is created, an
indexed variable can be used in the same way as a regular
variable.
0
0
0
0
0
0
0
0
0
0

• The following loop assigns 0 to myList[0], 1 to myList[1], ..., and 9 to


myList[9] :
for (int i = 0; i < myList.length; i++) {
myList[i] = i;
} 16
Introducing Arrays
• Array Indexed Variables: Some programming languages
use parentheses to reference an array element, as in
myList(9), but Java uses brackets, as in myList[9].

17
Array Initializers
• Java has a shorthand notation, known as the array
initializer, which combines the declaration, creation, and
initialization of an array in one statement :
elementType[] arrayRefVar = {value0, value1, ..., valuek};

• For example, the statement


double[] myList = {1.9, 2.9, 3.4, 3.5};


double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
18
Caution: Array Initializers
• The new operator is not used in the array-initializer syntax.
double[] myList = {1.9, 2.9, 3.4, 3.5};

• Using an array initializer, you have to declare, create, and


initialize the array all in one statement. Splitting it would
cause a syntax error.
double[] myList;
myList = {1.9, 2.9, 3.4, 3.5};

19
Processing Arrays
• When processing array elements, you will often use a for
loop—for two reasons:
1. All of the elements in an array are of the same type. They are
evenly processed in the same fashion repeatedly using a loop.
2. Since the size of the array is known, it is natural to use a for loop.

20
Processing Arrays, cont.
• Assume the array is created as follows :
double[] myList= new double[10];
The following are some examples of processing arrays.
1. Initializing arrays with input values.
2. Initializing arrays with random values.
3. Printing arrays.
4. Summing all elements.
5. Finding the largest element.
6. Finding the smallest index of the largest element.
7. Random shuffling.
8. Shifting elements.
21
9. Simplifying coding: “ Look up tables”
Initializing arrays with input values.
• The following loop initializes the array myList with user
input values.

22
Initializing arrays with random values
• The following loop initializes the array myList with random
values between 0.0 and 100.0, but less than 100.0.

23
Displaying or printing arrays
• To print an array, you have to print each element in the
array using a loop like the following:

24
Displaying or printing arrays
• To print an array, you have to print each element in the
array using a loop like the following:

• Tip : For an array of the char[] type, it can be printed using


one print statement. For example, the following code
displays Dallas:

25
Summing all elements
• Use a variable named total to store the sum. Initially total
is 0. Add each element in the array to total using a loop like
this:

26
Finding the largest element:
• Use a variable named max to store the largest element.
• Initially max is myList[0]. To find the largest element in the
array myList, compare each element with max, and update
max if the element is greater than max.

27
Finding the smallest index of the largest element
• Often you need to locate the largest element in an array.
• If an array has more than one largest element, find the
smallest index of such an element.
• Suppose the array myList is {1, 5, 3, 4, 5, 5}:
– The largest element is 5
– and the smallest index for 5 is 1.

28
Finding the largest element:
• Variable max will store the largest element and a variable
indexOfMax will store the index of the largest element.

29
Random shuffling
• In many applications, you need to randomly reorder the
elements in an array. This is called shuffling.
• To accomplish this, for each element myList[i], randomly
generate an index j and swap myList[i] with myList[j], as
follows:

30
Shifting elements
• Sometimes you need to shift the elements left or right.
• Here is an example of shifting the elements one position to
the left and filling the last element with the first element:

31
Simplifying coding: “ Look up tables”
• Arrays can be used to greatly simplify coding for certain
tasks.
• A lookup table, also known as LUT, is an array used in
computer programming that holds values which would
otherwise need to be calculated or searched.
– The table may be manually populated when the program is
written, or the program may populate the table with values as it
calculates them.
– When the values are needed later, the program can look them up,
saving CPU resources.

32
Simplifying coding: “ Look up tables”
• For example, suppose you wish to obtain the English name of a given
month by its number.
- If the month names are stored in an array, the month name for a
given month can be accessed simply via the index.

The following code prompts the user to enter a month number and
displays its month name:

33
Enhanced for Loop (for-each loop)
• JDK 1.5 introduced a new for loop, known as a “for-each loop” or
“enhanced for loop”, which enables you to traverse the array
sequentially without using an index variable. The following code
displays all the elements in the array myList:

• You can read the code as “for each element u in myList, do the
following.”
• Note that the variable, u, must be declared as the same type as the
elements in myList. In general, the syntax is

• You still have to use an index variable if you wish to traverse the array
34
in a different order or change the elements in the array.
Case Study: Lotto Numbers
• Each ticket for the “Pick-10 lotto” has 10 unique numbers
ranging from 1 to 99.

• Suppose you buy a lot of tickets and like to have them


cover all numbers from 1 to 99.

So the problem is to write a program that checks if all the


input numbers cover 1 to 99.

• We will use input redirection to read the numbers from a


file (assume the last number in the file is 0).

35
Case Study: Lotto Numbers, cont.
• Suppose the file contains the numbers

Your program should display: The tickets cover all numbers


• Suppose the file contains the numbers

Your program should display: The tickets don't cover all numbers
36
Case Study: Lotto Numbers, cont.
• How do you mark a number as covered?
You can create an array isCovered with 99 boolean elements.
Initially, each element is false. Whenever a number is read, its
corresponding element is set to true.
Suppose the numbers entered are 1, 2, 3, 99, 0. When number
1 is read, isCovered[0] is set to true (see b). When number 2 is
read, isCovered[2 - 1] is set to true (see c), etc.

37
Case Study: Lotto Numbers, cont.

True
True
True

True
True

38
Case Study: Lotto Numbers, cont.

Run
• Suppose you have created a text file named LottoNumbers.txt that
contains the input data
2 5 6 5 4 3 23 43 2 0.
You can run the program using the following command:
java LottoNumbers < LottoNumbers.txt
39
Case Study: Deck of Cards
• The problem is to create a program that will randomly
select four cards from a deck of 52 cards.
• All the cards can be represented using an array named
deck, filled with initial values 0 to 51.
• The values of the elements of the array represent the cards.

40
Case Study: Deck of Cards, cont.
• Card numbers 0 to 12 represent 13 Spades (‫)بستوني‬,
• 13 to 25 represent 13 Hearts,
• 26 to 38 represent 13 Diamonds (‫)الديناري‬,
• 39 to 51 represent 13 Clubs(‫)السباتي‬.

41
Case Study: Deck of Cards, cont.
• cardNumber / 13 determines the suit of
the card

• cardNumber % 13 determines the rank of


the card.

42
Case Study: Deck of Cards, cont.
• After shuffling the array deck, pick the first four cards from
deck

43
Case Study: Deck of Cards, cont.

Run

GUI Demo (picking four cards) 44


Copying Arrays
• To copy the contents of one array into another, you have to
copy the array’s individual elements into the other array.
• You could attempt to use the assignment statement (=)
list2 = list1;
This statement does not copy the contents of the array referenced by
list1 to list2, but the reference value from list1 to list2. After this
statement, list1 and list2 reference the same array.

Garbage
45
Copying Arrays, cont.
• There are 3 ways to copy arrays:

1. Use a loop to copy individual elements one by one.

2. Use the static arraycopy method in the System class.

3. Use the clone method; this method will be introduced


in Chapter 15, Abstract Classes and Interfaces

46
Copying Arrays with a loop
• You can write a loop to copy every element from the source
array to the corresponding element in the target array.

• The following code copies sourceArray to targetArray using


a for loop.
int[] sourceArray= {2, 3 ,1 ,5, 10};
int[] targetArray= new int[sourceArray.length];
for(int i=0; i<sourceArray.length;i++)
targetArray[i]=sourceArray[i];

47
Copying Arrays with the static arraycopy method
• Another approach is to use the arraycopy method in the
java.lang.System class to copy arrays instead of using a loop. The
syntax for arraycopy is:
arraycopy(sourceArray,src_pos,targetArray,tar_pos,length);

– The parameters src_pos and tar_pos indicate the starting


positions in sourceArray and targetArray, respectively.
– The number of elements copied from sourceArray to targetArray
48
is indicated by length.
Copying Arrays with the static arraycopy method
• Another approach is to use the arraycopy method in the
java.lang.System class to copy arrays instead of using a loop. The
syntax for arraycopy is:
arraycopy(sourceArray,src_pos,targetArray,tar_pos,length);

The arraycopy method does not allocate memory space for the
target array. The target array must have already been created with
its memory space allocated.
49
Copying Arrays with the static arraycopy method
• For exp, you can rewrite the loop
for(int i=0; i<sourceArray.length;i++)
targetArray[i]=sourceArray[i];
using the following statement:
System.arraycopy(sourceArray,0,targetArray,0,sourceArray.length);

• After the copying takes place, targetArray and sourceArray


have the same content but independent memory
locations.
• The arraycopy method violates the Java naming
convention. By convention, this method should be named
arrayCopy (i.e., with an uppercase C).
50
Passing Arrays to Methods
• When passing an array to a method, the reference of the
array is passed to the method.
• For example, the following method displays the elements in
an int array:

You can invoke it by passing an array. For example,


int[] list = {3, 1, 2, 6, 4, 2};
printArray(list);
or directly using
printArray(new int[] {3, 1, 2, 6, 4, 2});
51
Note: anonymous array
• The preceding statement
printArray(new int[] {3, 1, 2, 6, 4, 2});

creates an array using the following syntax:

There is no explicit reference variable for the array.

• Such array is called an anonymous array.

52
Passing Arrays to Methods, cont.
• Java uses pass-by-value to pass arguments to a method.
• There are important differences between passing primitive
data types and passing arrays to a method.
– For an argument of a primitive type, the argument’s value is
passed.

– For an argument of an array type, the argument’s value is a


reference to an array; this reference value is passed to the
method.

The array in the method is the same as the array being


passed. Thus, if you change the array in the method, you
will see the change outside the method.
53
Passing Arrays to Methods, cont.
• Take the following code, for example:

54
Passing Arrays to Methods, cont.
• When m(x, y) is invoked, the values of x and y are passed to
number and numbers.
0
0
0
0
0
0
0
0
0
0

• Since y contains the reference value to the array, numbers


now contains the same reference value to the same array.

55
Passing Arrays to Methods, cont.
• When m(x, y) is invoked, the values of x and y are passed to
number and numbers.
5555
0
0
0
1001 0
0
0
0
0
0

• If you change the array in the method, you will see the
change outside the method.

56
The Heap
• Arrays are objects in Java (objects are introduced in
Chapter 8).
5555
0
0
0
1001 0
0
0
0
0
0

• The JVM stores the objects in an area of memory called the


heap, which is used for dynamic memory allocation.

57
Passing Arrays to Methods, cont.
• The program contains 2 methods for swapping elements in an array.
– The 1st method, named swap, fails to swap two int arguments.
– The 2nd method, named swapFirstTwoInArray, successfully swaps
the first two elements in the array argument

58
Passing Arrays to Methods, cont.

Run
59
Passing Arrays to Methods, cont.

60
Returning an Array from a Method
• When a method returns an array, the reference of the array
is returned.
• The following method returns an array that is the reversal
of another array.

61
Trace the reverse Method
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1); On peut aussi écrire:
int[] list1 ={1, 2, 3, 4, 5, 6};

Declare result and create array


public static int[] reverse(int[] list) {
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 0 0 62
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i = 0 and j = 5
public static int[] reverse(int[] list) {
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 0 0 63
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i (= 0) is less than 6
public static int[] reverse(int[] list) {
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 0 0 64
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i = 0 and j = 5
public static int[] reverse(int[] list) { Assign list[0] to result[5]
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 0 1 65
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

After this, i becomes 1


public static int[] reverse(int[] list) {
and j becomes 4
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 0 1 66
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

public static int[] reverse(int[] list) {


i (=1) is less than 6
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 0 1 67
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i = 1 and j = 4
public static int[] reverse(int[] list) { Assign list[1] to result[4]
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 2 1 68
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

After this, i becomes


public static int[] reverse(int[] list) { 2 and j becomes 3
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 2 1 69
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i (=2) is still less


public static int[] reverse(int[] list) { than 6
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 2 1 70
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i = 2 and j = 3
public static int[] reverse(int[] list) { Assign list[i] to result[j]
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 0 3 2 1 71
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

After this, i becomes


public static int[] reverse(int[] list) { 3 and j becomes 2
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 0 3 2 1 72
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i (=3) is still less


public static int[] reverse(int[] list) { than 6
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 0 3 2 1 73
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i = 3 and j = 2
public static int[] reverse(int[] list) { Assign list[i] to result[j]
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 4 3 2 1 74
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

After this, i becomes


public static int[] reverse(int[] list) { 4 and j becomes 1
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 4 3 2 1 75
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i (=4) is still less


public static int[] reverse(int[] list) { than 6
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 4 3 2 1 76
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i = 4 and j = 1
public static int[] reverse(int[] list) { Assign list[i] to result[j]
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 5 4 3 2 1 77
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

After this, i becomes


public static int[] reverse(int[] list) { 5 and j becomes 0
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 5 4 3 2 1 78
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i (=5) is still less


public static int[] reverse(int[] list) { than 6
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 5 4 3 2 1 79
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i = 5 and j = 0
public static int[] reverse(int[] list) { Assign list[i] to result[j]
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 6 5 4 3 2 1 80
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

After this, i becomes


public static int[] reverse(int[] list) { 6 and j becomes -1
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 6 5 4 3 2 1 81
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i (=6) < 6 is false.


public static int[] reverse(int[] list) { So exit the loop.
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 6 5 4 3 2 1 82
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

Return result
public static int[] reverse(int[] list) {
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

list2
result 6 5 4 3 2 1 83
Case Study: Counting the Occurrences of Each Letter
• Write a program to count the occurrences of each letter in
an array of characters.
• The program does the following:
1. Generates 100 lowercase letters randomly and assigns them to
an array of characters.
2. Count the occurrences of each letter in the array.
To do so, create an array, say counts, of 26 int values, each of which
counts the occurrences of a letter.

84
Case Study: Counting the Occurrences of Each Letter

85
Case Study: Counting the Occurrences of Each Letter

86
Case Study: Counting the Occurrences of Each Letter

Run 87
Case Study: Counting the Occurrences of Each Letter
• The figure below shows the call stack and heap during and after
executing createArray.

88
Variable-Length Argument Lists
• A variable number of arguments of the same type can be
passed to a method and treated as an array.
For ex.
Public static int sum(int a, int ...numbers)

• In the method declaration, the variable-length parameter in


the method is declared as follows:
typeName ...parameterName

• Only one variable-length parameter may be specified in a


method, and this parameter must be the last parameter.

89
Variable-Length Argument Lists, cont.
• Listing 6.5 contains a method that prints the maximum value in a list
of an unspecified number of values Java treats a variable-length parameter as
an array. When invoking a method with a
variable number of arguments, Java creates
an array and passes the arguments to it.

90
Variable-Length Argument Lists, cont.
• Listing 6.5 contains a method that prints the maximum value in a list
of an unspecified number of values Java treats a variable-length parameter as an
array. When invoking a method with a
variable number of arguments, Java creates
an array and passes the arguments to it.

i.e., you can pass an array or a


variable number of arguments
to a variable-length parameter.

Run 91
Searching Arrays
• Searching is the process of looking for a specific element in
an array.

• Searching is a common task in computer programming.

• Many algorithms and data structures are devoted to


searching. We will discuss two commonly used approaches,
1. Linear search.
2. Binary search (requires an already sorted array).

92
Searching Arrays : Linear Search
• The linear search approach compares the key element key
sequentially with each element in the array. It continues to
do so until:
1. the key matches an element in the array,
2. or the array is exhausted without a match being found.
• If a match is made, the linear search returns the index of
the element in the array that matches the key.
• If no match is found, the search returns -1.

93
Searching Arrays : Linear Search
Key List
3 6 4 1 9 7 3 2 8
3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8
returns 5 94
Searching Arrays : Linear Search

• trace it with the following statements:


int[] list = {1, 4, 4, 2, 5, -3, 6, 2};
int i = linearSearch(list, 4); // Returns 1
int j = linearSearch(list, -4); // Returns -1
int k = linearSearch(list, -3); // Returns 5 95
Searching Arrays : Binary Search
• For binary search to work, the elements in the array must
already be ordered.

• Assume that the array is in ascending order. The binary


search first compares the key with the element in the
middle of the array. Consider the following three cases:
1. If the 𝑘𝑒𝑦 < 𝑚𝑖𝑑𝑑𝑙𝑒 𝑒𝑙𝑒𝑚𝑒𝑛𝑡, continue to search for the key
only in the 1st half of the array.

2. If the 𝑘𝑒𝑦 = 𝑚𝑖𝑑𝑑𝑙𝑒 𝑒𝑙𝑒𝑚𝑒𝑛𝑡, the search ends with a match.


3. If the 𝑘𝑒𝑦 > 𝑚𝑖𝑑𝑑𝑙𝑒 𝑒𝑙𝑒𝑚𝑒𝑛𝑡, continue to search for the key
only in the 2nd half of the array.
96
Searching Arrays : Binary Search

Key List

8 1 2 3 4 6 7 8 9
8 1 2 3 4 6 7 8 9

8 1 2 3 4 6 7 8 9

97
Searching Arrays : Binary Search bechmarking
• Clearly, the binary search method eliminates at least half of
the array after each comparison.

• Suppose that the array has n elements. For convenience, let


n be a power of 2.
– After the 1st comparison, 𝒏/𝟐 elements are left for further search;
𝟏
– after the 2nd comparison, (𝒏/𝟐) × elements are left.
𝟐

– After the kth comparison, 𝒏/𝟐𝒌 elements are left for further
search.

– When 𝒌 = log𝟐𝒏, only one element is left in the array, and you
need only one more comparison. 98
Searching Arrays : Binary Search bechmarking
• Therefore, in the worst case when using the binary search
approach, you need log𝟐𝒏 + 𝟏 comparisons to find an
element in the sorted array.

• In the worst case for a list of 1024 (210) sorted elements,


– binary search requires only 11 comparisons,
– linear search requires 1023 comparisons.

99
Searching Arrays : Binary Search, cont.
=(low+high)/2

New low=low
New high=mid-1
𝑙𝑜𝑤+ℎ𝑖𝑔ℎ
= 2
New low=mid+1
New high=high

100
Searching Arrays : Binary Search, cont.
key is 54 low mid =(low+high)/2 high

key > 50 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
New low=mid+1
New high=high list 2 4 7 10 11 45 50 59 60 66 69 70 79

low mid high


New low=low
New high=mid-1 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
key < 66 list 59 60 66 69 70 79

low mid high


New low=low
New high=mid-1
[7] [8]
key < 59 list 59 60

low high

[6] [7] [8]


59 60 101
Binary Search From Idea to Solution
• You now know how the binary search works. The next task
is to implement it. Don’t rush, implement incrementally:
– You may start with the 1st iteration of the search, as shown in (a),
– Next consider implementing the method to perform the search
repeatedly by adding a loop, as shown in (b)

102
Binary Search From Idea to Solution, cont.
• The binarySearch method returns the index of the element in the list
that matches the search key if it is contained in the list. Otherwise -1.
• It is better to return “-insertion point – 1” than (-1).

103
Binary Search From Idea to Solution, cont.
• The insertion point is the point at which an unmatched key would be
inserted into the list.
low high
Key is 54
[6] [7] [8]
50 59 60

Why don’t we just return


“-insertion point”
instead of
“-insertion point-1” ?

104
Binary Search: implementation
• Does the method still work if there are duplicate elements in the list?
Yes, as long as the elements are sorted in increasing order. The method
returns the index of one of the matching elements if the element is in
the list.

105
The Arrays.binarySearch Method
• Java provides several overloaded binarySearch methods for
searching a key in an array of int, double, char, short, long,
and float in the java.util.Arrays class.
For example, the following code searches the keys in an
array of numbers
int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79};
System.out.println("Index is " + java.util.Arrays.binarySearch(list, 11));
Return is 4

and an array of characters.


char[] chars = {'a', 'c', 'g', 'x', 'y', 'z'};
System.out.println("Index is " +java.util.Arrays.binarySearch(chars, 't'));
Return is –4 (insertion point is 3, so return is -3-1)
106
Sorting Arrays
• There are many strategies for sorting elements in an array.
1. Selection sort
2. Insertion sort
are two common approaches.

107
Sorting Arrays : Selection sort
• Selection Sort
Suppose that you want to sort a list in ascending order.
1. Selection sort finds the smallest number in the list and
swaps it with the first element.
2. It then finds the smallest number remaining and swaps
it with the second element,
3. and so on, until only a single number remains.

108
Sorting Arrays : Selection sort
• The figure shows how to sort the list {2, 9, 5, 4, 8, 1, 6}
using selection sort.
1

2 3

4 5

6 7

8 9

10 11

12 13 109
From Idea to Solution
• The solution can be described as follows:

list[0] list[1] list[2] list[3] ... list[10]

list[0] list[1] list[2] list[3] ... list[10]

list[0] list[1] list[2] list[3] ... list[10]

list[0] list[1] list[2] list[3] ... list[10]

list[0] list[1] list[2] list[3] ... list[10]

...

list[0] list[1] list[2] list[3] ... list[10]


110
From Idea to Solution
• The solution can be described as follows:

Expand
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i+1; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
} 111
From Idea to Solution
• The solution can be described as follows:

Expand
if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}

112
Wrap it in a Method

113
Sorting Arrays : Insertion sort
• The insertion-sort algorithm sorts a list of values by repeatedly
inserting a new element into a sorted sublist until the whole list is
sorted.
sorting the list
{2, 9, 5, 4, 8, 1, 6}
using insertion sort

114
Sorting Arrays : Insertion sort
• Sorting the list {2, 9, 5, 4, 8, 1, 6} using insertion sort

2 9 5 4 8 1 6
2 9 5 4 8 1 6
2 5 9 4 8 1 6
2 4 5 9 8 1 6
2 4 5 8 9 1 6
1 2 4 5 8 9 6
1 2 4 5 6 8 9

115
Insertion sort: How to Insert?
• The algorithm can be described as follows:

• To insert list[i] into list[0…i-1],


1. save list[i] into a temporary variable, say
currentElement.
2. Move list[i-1] to list[i] if list[i-1] > currentElement,
3. move list[i-2] to list[i-1] if list[i-2] > currentElement,
and so on, until list[i-k] <= currentElement or k > i (we
pass the first element of the sorted list).
4. Assign currentElement to list[i-k+1]. 116
Insertion sort: How to Insert?
• For exp., to insert list[3] = 4 into sorted list[0…2] ={2, 5, 9}:
1. save list[3] into a temporary variable “currentElement”
2. move list[2] (9) to list[3] since 9 > 4,
3. and move list[1] (5) to list[2] since 5 > 4.
4. Finally, move currentElement (4) to list[1].

117
Insertion sort: implementation

• To better understand this method, trace it with the


following statements:
118
The Arrays Class
• The java.util.Arrays class contains useful methods for
common array operations such as
1. sorting
2. searching.
3. comparing arrays,
4. filling array elements,
5. returning a string representation of the array.
These methods are overloaded for all primitive types.

119
The Arrays Class: sorting
• You can use the sort method to sort a whole array or a
partial array

• Invoking sort(numbers) sorts the whole array numbers.


• Invoking sort(chars, 1, 3) sorts a partial array from chars[1]
to chars[3-1].

120
The Arrays Class: searching
• You can use the binarySearch method to search for a key in
an array.
• The array must be pre-sorted in increasing order.
• If the key is not in the array, the method returns
–(insertionindex + 1).

121
The Arrays Class: equals
• You can use the equals method to check whether two
arrays are equal.
• Two arrays are equal if they have the same contents.

122
The Arrays Class: filling
• You can use the fill method to fill in all or part of the array.
• the following code:
– fills list1 with 5
– and fills 8 into elements list2[1] to list2[3-1].

123
The Arrays Class: toString
• You can also use the toString method to return a string that
represents all elements in the array.

124
Homework
• Study all materials in chapter 6 from the textbook.
• Exercises:
6.3, 6.5, 6.6, 6.7, 6.11, 6.12, 6.15, 6.16, 6.18, 6.19,
6.21, 6.23, 6.24, 6.25, 6.27, 6.28, 6.30,6.31, 6.32.
from chapter 6

125

You might also like