Professional Documents
Culture Documents
Objectives
After studying this chapter, you should be
able to:
Elaborate the use of arrays.
Declare and use an array of primitive data types
in writing a program.
Apply array of objects in developing a program
Apply the principles of arrays in linear search
(sequential search) and bubble sort.
Array Basics
An array is a collection of data values.
If your program needs to deal with 100 integers, 500
Account objects, 365 real numbers, etc., you will use
an array.
In Java, an array is an indexed collection of data values
of the same type.
Types of Arrays:
- one-dimensional array
- two-dimensional array
- multidimensional array
3
Array Creation
<variable>
Example
Variation 2
double[ ] rainfall;
double rainfall [ ];
rainfall
rainfall
= new double[12];
= new double[12];
rainfall
rainfall[2]
10
11
This
Thisindexed
indexedexpression
expression
refers
to
the
element
refers to the elementatat
position
position#2
#2
The
Thepublic
publicconstant
constant
length
returns
length returnsthe
the
capacity
of
an
capacity of an
array.
array.
=Double.parseDouble(input.readLine());
sum += rainfall[i];
}
annualAverage = sum / rainfall.length;
The
Thesame
samepattern
pattern
for
the
remaining
for the remaining
ten
tenmonths.
months.
Array Initialization
Like other data types, it is possible to declare
and initialize an array at the same time.
int[] number = { 2, 4, 6, 8 };
double[] samplingData = { 2.443, 8.99, 12.3, 45.009, 18.2,
9.00, 3.123, 22.084, 18.08 };
String[] monthName = { "January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December" };
number.length
samplingData.length
monthName.length
4
9
12
10
Variable-size Declaration
In Java, we are not limited to fixed-size array
declaration.
The following code prompts the user for the size of an
array and declares an array of designated size:
int size;
int[] number;
System.out.print(Size of Array :);
size= Integer.parseInt(input.readLine());
number = new int[size];
11
Arrays of Objects
In Java, in addition to arrays of primitive
data types, we can declare arrays of objects
Can use arrays to manipulate objects.
The use of an array of objects allows us to
model the application more cleanly and
logically.
12
Code
Person[ ]
person;
Only
Onlythe
thename
nameperson
person
isisdeclared,
no
array
declared, no arrayisis
allocated
allocatedyet.
yet.
Person( );
person
State
of
Memor
y
A is executed
After A
13
Code
B
B
person;
Now
Nowthe
thearray
arrayfor
forstoring
storing
20
Person
objects
is
20 Person objects is
created,
created,but
butthe
thePerson
Person
objects
themselves
objects themselvesare
are
not
yet
created.
not yet created.
person
State
of
Memor
y
After B
B is executed
16 17 18 19
14
Code
person;
C
C
One
OnePerson
Personobject
objectisis
created
createdand
andthe
thereference
reference
totothis
object
is
placed
this object is placedinin
position
position0.0.
person
State
of
Memor
y
16 17 18 19
Person
After C
C is executed
15
18
19
20
minIdx = 0;
int
maxIdx = 0;
= i;
= i;
}
}
//person[minIdx] is the youngest and person[maxIdx] is the oldest
22
int delIdx = 1;
A
A
person[delIdx] = null;
person
person
0
AA
BB
CC
D
D
Before A
A is executed
AA
CC
D
D
After A
A is executed
23
A
A
person[delIndex] = person[last];
person[last]
person
= null;
person
0
AA
Delete
DeletePerson
PersonBBby
by
setting
the
reference
setting the referenceinin
position
position11totothe
thelast
last
person.
person.
BB
CC
D
D
Before A
A is executed
AA
D
D
CC
After A
A is executed
24
25
Code
A
A
minOne
= searchMinimum(arrayOne);
At
A
A before searchMinimum
arrayOne
State of
Memory
A.
A.Local
Localvariable
variable
number
numberdoes
does not
not
exist
before
the
exist before the
method
methodexecution
execution
26
B
B
B
The address is copied at B
arrayOne
State of
Memory
number
B.
B.The
Thevalue
valueofofthe
the
argument,
argument,which
whichisis
an
anaddress,
address,isis
copied
copiedtotothe
the
parameter.
parameter.
27
C
C
While at C
C inside the method
arrayOne
State of
Memory
number
C.
C.The
Thearray
arrayisis
accessed
accessedvia
via
number
inside
number inside
the
themethod.
method.
28
minOne
= searchMinimum(arrayOne);
D after searchMinimum
At D
arrayOne
arrayOne
State of
Memory
number
D.
D.The
Theparameter
parameterisis
erased.
erased.The
Theargument
argument
still
points
to
the
still points to thesame
same
object.
object.
29
Two-Dimensional Arrays
Two-dimensional arrays are useful in representing tabular information.
30
Two-Dimensional Arrays
Declaration a two-dimensional arrays
<data type> [][] <variable>
<data type>
<variable>[][]
//variation 1
//variation 2
Example
double[][] payScaleTable;
payScaleTable
= new double[4][5];
payScaleTable
0
1
2
3
31
Two-Dimensional Arrays
An element in a two-dimensional array is
accessed by its row and column index.
32
Two-Dimensional Arrays
Find the average of each row.
double[ ] average = { 0.0, 0.0, 0.0, 0.0 };
for (int i = 0; i < payScaleTable.length; i++) {
for (int j = 0; j < payScaleTable[i].length; j++) {
average[i] += payScaleTable[i][j];
}
average[i] = average[i] / payScaleTable[i].length;
}
33
Array Applications
Searching
Linear Search
Binary Search
Sorting
Bubble sort
Insertion Sort
Selection Sort
Linear Search
The linear search is also known as sequential
search, compares the key element, key,
sequentially with each element in the array list.
The method continues to do so until the key
matches an element in the list or the list 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.
36
Linear Search
/** The method for finding a key in the list */
public static int linearSearch(int[] list, int key) {
for (int i = 0; i < list.length; i++)
if (key == list[i])
return i;
return -1;
}
Linear Search
public class Search{
public void printout(int marks[ ])
{
System.out.print("Elements of Array :");
for (int k=0; k <marks.length; k++)
System.out.print( marks[k] + "\t");
System.out.println();
} // end printout method
public int searchLinear(int marks[ ], int key)
{
for (int k=0; k <marks.length; k++)
if (marks[k] == key)
return k; // return indeks if found
return 1; // return 1 if not found
} // end searchLinear method
38
Linear Search
public static void main(String [] arg)
{
int studMark [ ] = {21,20,27,24,19};
Search searching = new Search();
searching.printout(studMark);
int a= searching.searchLinear(studMark,24);
System.out.println("Index = " + a);
int b = searching.searchLinear(studMark,5);
System.out.println("Index = " + b);
} // end main
} // end class
39
Linear Search
Output:
Elements of Array :21 20 27 24 19
Index = 3
Index = 1
Process Exit...
40
Bubble Sort
Sort the elements of array in increasing
order.
Example : 10 7 19 5 16
sort in increasing order
5 7 10 16 19
41
Bubble Sort
The bubble sort algorithm works as follows:
Suppose list[0].list[n-1] is a list of n elements, indexed 0 to
n-1.
list [0] [1] [2] [3] [4]
21 20 27 24 19
In a series of n 1 iterations, the successive elements,
list[index] and list[index +1] of list are compared. If list[index]
is greater than list [index + 1], then the elements list[index] and
list[index +1] are swapped, that is, interchanged.
It follows that the smaller elements move toward the top, and
the larger elements move towards the bottom.
42
Bubble Sort
Iteration 1
Iteration 2
21 20 27 24 19
20 21 24 19 27
20 21 27 24 19
20 21 24 19 27
20 21 27 24 19
20 21 24 19 27
20 21 24 27 19
20 21 19 24 27
20 21 24 19 27
20 21 19 24 27
43
Bubble Sort
Iteration 3
Iteration 4
20 21 19 24 27
20 19 21 24 27
20 21 19 24 27
19 20 21 24 27
20 19 21 24 27
19 20 21 24 27
20 19 21 24 27
19 20 21 24 27
19 20 21 24 27
20 19 21 24 27
sorted list : 19 20 21 24 27
44
Bubble Sort
public class TestBubbleSort {
void bubbleSort(int list[], int listLength)
{
int temp;
int counter, index;
for(counter=0; counter <listLength -1; counter++)
{
for(index=0; index<listLength-1-counter;index++)
if (list[index] > list[index +1]){
temp = list[index];
list[index] = list[index +1];
list[index + 1] = temp;
}
}
}
45
Bubble Sort
public static void main(String[] args)
{
int list[]={10, 7, 19, 5};
int i;
TestBubbleSort sort = new TestBubbleSort();
sort.bubbleSort(list, 4);
System.out.print("After sorting, the list
elements are:");
for(i=0; i<4; i++)
System.out.print(list[i] + "");
System.out.println();
}
}
46
Bubble Sort
Output:
After sorting, the list elements are:
5 7 10 19
47
References
Thomas Wu. C, An Introduction To Object-
48
Exercise
Look at your handout.
Read and understand
the given instruction.
Answer now.
49