Introduction To Java Programming Chapter 6: Single-Dimensional Arrays
Introduction To Java Programming Chapter 6: Single-Dimensional Arrays
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.
Run 3
Introducing Arrays
• An array is a collection of variables of the same type.
• The elementType can be any data type, and all elements in the
array will have the same data type.
double[] myList;
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];
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,
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
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
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};
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};
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:
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.
35
Case Study: Lotto Numbers, cont.
• 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
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
Garbage
45
Copying Arrays, cont.
• There are 3 ways to copy arrays:
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.
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 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);
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.
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
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
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};
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];
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];
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];
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);
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);
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];
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);
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);
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];
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);
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);
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];
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);
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);
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];
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);
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);
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];
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);
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);
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];
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)
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.
Run 91
Searching Arrays
• Searching is the process of looking for a specific element in
an 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
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.
– 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.
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 high
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
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
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:
...
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:
117
Insertion sort: implementation
119
The Arrays Class: sorting
• You can use the sort method to sort a whole array or a
partial array
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