0% found this document useful (0 votes)
40 views50 pages

Chapter3 Lecture4 Array

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 50

Chapter 3 Arrays

1
Introducing Arrays
Array is a data structure that represents a collection of the
same types of data.
double[] myList = new double[10];

myList reference
myList[0] 5.6
myList[1] 4.5
Array reference myList[2] 3.3
variable
myList[3] 13.2

myList[4] 4
Array element at
myList[5] 34.33 Element value
index 5
myList[6] 34

myList[7] 45.45

myList[8] 99.993

myList[9] 11123

2
Declaring Array Variables
• datatype[] arrayRefVar;
Example:
double[] myList;

• datatype arrayRefVar[]; // This style is


allowed, but not preferred
Example:
double myList[];

3
Creating Arrays
arrayRefVar = new datatype[arraySize];

Example:
myList = new double[10];

myList[0] references the first element in the array.


myList[9] references the last element in the array.

4
Declaring and Creating in One
Step
• datatype[] arrayRefVar = new
datatype[arraySize];
double[] myList = new double[10];

• datatype arrayRefVar[] = new


datatype[arraySize];
double myList[] = new double[10];

5
The Length of an Array
Once an array is created, its size is fixed. It cannot be
changed. You can find its size using

arrayRefVar.length

For example,

myList.length returns 10

6
Default Values
When an array is created, its elements are
assigned the default value of

0 for the numeric primitive data types,


'\u0000' for char types, and
false for boolean types.

7
Indexed Variables
The array elements are accessed through the index.
The array indices are 0-based, i.e., it starts from 0 to
arrayRefVar.length-1. In the example, 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];

8
Using Indexed Variables
After an array is created, an indexed variable can
be used in the same way as a regular variable.
For example, the following code adds the value
in myList[0] and myList[1] to myList[2].

myList[2] = myList[0] + myList[1];

9
Array Initializers

• Declaring, creating, initializing in one step:


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

This shorthand syntax must be in one


statement.

10
Declaring, creating, initializing Using the
Shorthand Notation
double[] myList = {1.9, 2.9, 3.4, 3.5};

This shorthand notation is equivalent to the


following statements:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;

11
Out of Bounds
Errors
• It is a dangerous mistake to attempt to index into an array a
using a number outside the range from 0 to myList.length
minus 1.
• Such a reference is said to be out of bounds.
• If an array index is out of bounds, the run-time Java
environment signals an error condition.
• The name of this condition is the
ArrayIndexOutOfBoundsException

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 12
rights reserved. 0132130807
CAUTION
Using the shorthand notation, you have to declare,
create, and initialize the array all in one statement.
Splitting it would cause a syntax error. For example, the
following is wrong:

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

13
Trace Program with Arrays
Declare array variable values, create an
array, and assign its reference to values

public class Test {


public static void main(String[] args) { After the array is created
int[] values = new int[5];
for (int i = 1; i < 5; i++) { 0 0
values[i] = i + values[i-1]; 1 0
} 0
2
values[0] = values[1] + values[4];
3 0
}
4 0
}

14
animation
Trace Program with Arrays
i becomes 1

public class Test {


public static void main(String[] args) {
After the array is created
int[] values = new int[5];
for (int i = 1; i < 5; i++) { 0 0

values[i] = i + values[i-1]; 1 0

} 2 0

0
values[0] = values[1] + values[4];
3

4 0
}
}

15
Trace Program with Arrays
i (=1) is less than 5

public class Test {


public static void main(String[] args) {
int[] values = new int[5]; After the array is created

for (int i = 1; i < 5; i++) { 0 0


values[i] = i + values[i-1]; 1 0

} 2 0

values[0] = values[1] + values[4]; 3 0

} 4 0

16
Trace Program with Arrays
After this line is executed, value[1] is 1

public class Test {


public static void main(String[] args) { After the first iteration

int[] values = new int[5]; 0 0


for (int i = 1; i < 5; i++) { 1 1
values[i] = i + values[i-1]; 2 0

} 3 0

values[0] = values[1] + values[4]; 4 0

}
}

17
Trace Program with Arrays
After i++, i becomes 2

public class Test {


public static void main(String[] args) {
int[] values = new int[5]; After the first iteration

for (int i = 1; i < 5; i++) {


0 0
values[i] = i + values[i-1]; 1 1

} 2 0

0
values[0] = values[1] + values[4];
3

4 0
}
}

18
Trace Program with Arrays

i (= 2) is less than 5
public class Test {
public static void main(String[]
args) {
int[] values = new int[5]; After the first iteration

for (int i = 1; i < 5; i++) { 0 0


values[i] = i + values[i-1]; 1 1

} 2 0

values[0] = values[1] + 3 0

values[4]; 4 0

}
}

19
Trace Program with Arrays
After this line is executed,
values[2] is 3 (2 + 1)

public class Test {


public static void main(String[] args) { After the second iteration

int[] values = new int[5]; 0 0


for (int i = 1; i < 5; i++) { 1 1
values[i] = i + values[i-1]; 2 3

} 3 0

values[0] = values[1] + values[4]; 4 0

}
}

20
Trace Program with Arrays
After this, i becomes 3.

public class Test {


public static void main(String[] args) { After the second iteration

int[] values = new int[5]; 0 0


for (int i = 1; i < 5; i++) { 1 1
values[i] = i + values[i-1]; 2 3

} 3 0

values[0] = values[1] + values[4]; 4 0

}
}

21
Trace Program with Arrays
i (=3) is still less than 5.

public class Test {


public static void main(String[] args) { After the second iteration

int[] values = new int[5]; 0 0


for (int i = 1; i < 5; i++) { 1 1
values[i] = i + values[i-1]; 2 3

} 3 0

values[0] = values[1] + values[4]; 4 0

}
}

22
Trace Program with Arrays
After this line, values[3] becomes 6 (3 + 3)

public class Test {


public static void main(String[] args) { After the third iteration

int[] values = new int[5]; 0 0


for (int i = 1; i < 5; i++) { 1 1
values[i] = i + values[i-1]; 2 3

} 3 6

values[0] = values[1] + values[4]; 4 0

}
}

23
Trace Program with Arrays
After this, i becomes 4

public class Test {


public static void main(String[] args) { After the third iteration

int[] values = new int[5]; 0 0


for (int i = 1; i < 5; i++) { 1 1
values[i] = i + values[i-1]; 2 3

} 3 6

values[0] = values[1] + values[4]; 4 0

}
}

24
Trace Program with Arrays
i (=4) is still less than 5

public class Test {


public static void main(String[] args) { After the third iteration

int[] values = new int[5]; 0 0


for (int i = 1; i < 5; i++) { 1 1
values[i] = i + values[i-1]; 2 3

} 3 6

values[0] = values[1] + values[4]; 4 0

}
}

25
Trace Program with Arrays
After this, values[4] becomes 10 (4 + 6)

public class Test {


public static void main(String[] args) { After the fourth iteration

int[] values = new int[5]; 0 0


for (int i = 1; i < 5; i++) { 1 1
values[i] = i + values[i-1]; 2 3

} 3 6

values[0] = values[1] + values[4]; 4 10

}
}

26
Trace Program with Arrays
After i++, i becomes 5

public class Test {


public static void
main(String[] args) {
int[] values = new
int[5];
for (int i = 1; i < 5; i++) { After the fourth iteration
values[i] = i + values[i-
1]; 0 0
} 1 1

values[0] = values[1] + 2 3
values[4]; 3 6
} 4 10
}

27
Trace Program with Arrays
i ( =5) < 5 is false. Exit the loop

public class Test {


public static void main(String[] args)
{
int[] values = new int[5];
for (int i = 1; i < 5; i++) { After the fourth iteration
values[i] = i + values[i-1];
} 0 0
values[0] = values[1] + values[4]; 1 1
}
} 2 3

3 6

4 10

28
Trace Program with Arrays
After this line, values[0] is 11 (1 + 10)

public class Test {


public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1]; 0 11
} 1 1
values[0] = values[1] + values[4]; 2 3
}
3 6
}
4 10

29
Processing Arrays
See the examples in the text.
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)

30
Initializing arrays with input values
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter " + myList.length + " values: ");
for (int i = 0; i < myList.length; i++)
myList[i] = input.nextDouble();

31
Initializing arrays with random values

for (int i = 0; i < myList.length; i++) {


myList[i] = Math.random() * 100;
}

32
Printing arrays

for (int i = 0; i < myList.length; i++) {


System.out.print(myList[i] + " ");
}

33
Summing all elements

double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}

34
Finding the largest element

double max = myList[0];


for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}

35
Copying Arrays
Often, in a program, you need to duplicate an array or a part of an
array. In such cases you could attempt to use the assignment
statement (=), as follows:

list2 = list1;
Before the assignment After the assignment
list2 = list1; list2 = list1;

list1 list1
Contents Contents
of list1 of list1

list2 list2
Contents Contents
of list2 of list2
Garbage

36
Copying Arrays
Using a loop:
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new
int[sourceArray.length];

for (int i = 0; i < sourceArrays.length; i++)


targetArray[i] = sourceArray[i];

37
The arraycopy Utility
arraycopy(sourceArray, src_pos,
targetArray, tar_pos, length);

Example:
System.arraycopy(sourceArray, 0,
targetArray, 0, sourceArray.length);

38
Sorting Arrays

 Sorting, like searching, is also a


common task in computer
programming.
 Many different algorithms have been
developed for sorting.
 This section introduces two simple,
intuitive sorting algorithms: selection
sort and insertion sort.

39
Selection Sort
Selection sort finds the largest number in the list and places it last. It then finds
the largest number remaining and places it next to last, and so on until the list
contains only a single number. Figure 6.17 shows how to sort the list {2, 9, 5, 4,
8, 1, 6} using selection sort.
sw a p

S elec t 1 (th e sm a lles t) a n d s w a p it 2 9 5 4 8 1 6


w ith 2 (th e firs t) in th e list
sw a p
T h e n u m b er 1 is n o w in th e
S elec t 2 (th e sm a lles t) a n d s w a p it 1 9 5 4 8 2 6 c o rrec t p o sitio n an d thu s n o
w ith 9 (th e firs t) in th e rem a in in g lo n g er n e ed s to b e c o n sid ered .
list sw a p

T h e n u m b er 2 is n o w in th e
S elec t 4 (th e sm a lles t) a n d s w a p it 1 2 5 4 8 9 6 c o rrec t p o sitio n an d thu s n o
w ith 5 (th e firs t) in th e rem a in in g lo n g er n e ed s to b e c o n s id ered .
list
T h e n u m b er 6 is n o w in th e
5 is th e sm a llest an d in th e righ t 1 2 4 5 8 9 6 c o rrec t p o sitio n an d thu s n o
p o s itio n . N o sw a p is n ec es sa ry lo n g er n e ed s to b e c o n s id ered .
sw a p

T h e n u m b er 5 is n o w in th e
S elec t 6 (th e sm a lles t) a n d s w a p it 1 2 4 5 8 9 6 c o rrec t p o sitio n an d thu s n o
w ith 8 (th e first) in th e rem a in in g lo n g er n e ed s to b e c o n s id ered .
list sw a p

T h e n u m b er 6 is n o w in th e
S elec t 8 (th e sm a lles t) a n d s w a p it 1 2 4 5 6 9 8 c o rrec t p o sitio n an d thu s n o
w ith 9 (th e first) in th e rem a in in g lo n g er n e ed s to b e c o n s id ered .
list

T h e n u m b er 8 is n o w in th e
S in c e th ere is o n ly o n e elem en t 1 2 4 5 6 8 9 c o rrec t p o sitio n an d th u s n o
rem a in in g in th e list, so rt is lo n g er n e ed s to b e c o n sid ered .
c o m p leted
40
From Idea to Solution
for (int i = 0; i < list.length; i++)
{
select the smallest element in list[i..listSize-1];
swap the smallest with list[i], if necessary;
// list[i] is in its correct position.
// The next iteration apply on list[i..listSize-1]
}

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]


41
for (int i = 0; i < listSize; i++)
{
select the smallest element in list[i..listSize-1];
swap the smallest with list[i], if necessary;
// list[i] is in its correct position.
// The next iteration apply on list[i..listSize-1]
}
Expand
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}

42
for (int i = 0; i < listSize; i++)
{
select the smallest element in list[i..listSize-1];
swap the smallest with list[i], if necessary;
// list[i] is in its correct position.
// The next iteration apply on list[i..listSize-1]
}
Expand
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}

43
for (int i = 0; i < listSize; i++)
{
select the smallest element in list[i..listSize-1];
swap the smallest with list[i], if necessary;
// list[i] is in its correct position.
// The next iteration apply on list[i..listSize-1]
}
Expand
if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}

44
Wrap it in a Method
/** The method for sorting the numbers */
public static void selectionSort(double[] list) {
for (int i = 0; i < list.length; i++) {
// Find the minimum in the list[i..list.length-1]
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;
}
}
// Swap list[i] with list[currentMinIndex] if necessary;
if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
}
}
Invoke it selectionSort(yourList)
45
Insertion Sort
int[] myList = {2, 9, 5, 4, 8, 1, 6}; // Unsorted
The insertion sort Step 1: Initially, the sorted sublist contains the 2 9 5 4 8 1 6
algorithm sorts a list first element in the list. Insert 9 to the sublist.

of values by
Step2: The sorted sublist is {2, 9}. Insert 5 to the
repeatedly inserting sublist.
2 9 5 4 8 1 6

an unsorted element
into a sorted sublist Step 3: The sorted sublist is {2, 5, 9}. Insert 4 to 2 5 9 4 8 1 6
the sublist.
until the whole list
is sorted. Step 4: The sorted sublist is {2, 4, 5, 9}. Insert 8 2 4 5 9 8 1 6
to the sublist.

Step 5: The sorted sublist is {2, 4, 5, 8, 9}. Insert 2 4 5 8 9 1 6


1 to the sublist.

Step 6: The sorted sublist is {1, 2, 4, 5, 8, 9}. 1 2 4 5 8 9 6


Insert 6 to the sublist.

Step 7: The entire list is now sorted 1 2 4 5 6 8 9

46
animation Insertion
Sort
int[] myList = {2, 9, 5, 4, 8, 1, 6}; // Unsorted

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

47
How to Insert?
The insertion sort algorithm sorts a list of values by repeatedly inserting
an unsorted element into a sorted sublist until the whole list is sorted.

[0] [1] [2] [3] [4] [5] [6]


list 2 5 9 4 Step 1: Save 4toa temporaryvariable currentElement

[0] [1] [2] [3] [4] [5] [6]


list 2 5 9 Step 2: Move list[2] to list[3]

[0] [1] [2] [3] [4] [5] [6]


list 2 5 9 Step 3: Move list[1] to list[2]

[0] [1] [2] [3] [4] [5] [6]


list 2 4 5 9 Step 4: Assign currentElement to list[1]
48
From Idea to Solution
for (int i = 1; 1; i < list.length; i++) {
insert list[i] into a sorted sublist list[0..i-1] so that
list[0..i] is sorted
}

list[0]

list[0] list[1]

list[0] list[1] list[2]

list[0] list[1] list[2] list[3]

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

InsertSort
49
The Arrays.sort Method
Since sorting is frequently used in programming, Java provides several
overloaded sort methods for sorting an array of int, double, char, short,
long, and float in the java.util.Arrays class. For example, the following
code sorts an array of numbers and an array of characters.

double[] numbers = {6.0, 4.4, 1.9, 2.9, 3.4, 3.5};


java.util.Arrays.sort(numbers);

char[] chars = {'a', 'A', '4', 'F', 'D', 'P'};


java.util.Arrays.sort(chars);

50

You might also like