Chapter 7 - Arrays: 2003 Prentice Hall, Inc. All Rights Reserved
Chapter 7 - Arrays: 2003 Prentice Hall, Inc. All Rights Reserved
Chapter 7 - Arrays: 2003 Prentice Hall, Inc. All Rights Reserved
Outline
7.1 Introduction
7.2 Arrays
7.3 Declaring and Creating Arrays
7.4 Examples Using Arrays
7.5 References and Reference Parameters
7.6 Passing Arrays to Methods
7.7 Sorting Arrays
7.8 Searching Arrays: Linear Search and Binary Search
7.9 Multidimensional Arrays
7.10 (Optional Case Study) Thinking About Objects:
Collaboration Among Objects
• Arrays
– Data structures
– Related data items of same type
– Remain same size once created
• Fixed-length entries
• Array
– Group of variables
• Have same type
– Reference type
• Index
– Also called subscript
– Position number in square brackets
– Must be positive integer or integer expression
a = 5;
b = 6;
c[ a + b ] += 2;
• Adds 2 to c[ 11 ]
• Examine array c
– c is the array name
– c.length accesses array c’s length
– c has 12 elements ( c[0], c[1], … c[11] )
• The value of c[0] is –45
• Declaring arrays
• Creating arrays
• Initializing arrays
• Manipulating array elements
InitArray.java
InitArray.java
PassArray.java
• Sorting data
– Attracted intense research in computer-science field
– Bubble sort
• Smaller values “bubble” their way to top of array
• Larger values “sink” to bottom of array
• Use nested loops to make several passes through array
– Each pass compares successive pairs of elements
• Pairs are left along if increasing order (or equal)
• Pairs are swapped if decreasing order
BinarySearch.ja
va
• Multidimensional arrays
– Tables with rows and columns
• Two-dimensional array
• Declaring two-dimensional array b[2][2]
int b[][] = { { 1, 2 }, { 3, 4 } };
– 1 and 2 initialize b[0][0] and b[0][1]
– 3 and 4 initialize b[1][0] and b[1][1]
int b[][] = { { 1, 2 }, { 3, 4, 5 } };
– row 0 contains elements 1 and 2
– row 1 contains elements 3, 4 and 5
Row 0
a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
Row 1
a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
Row 2
a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]
Column index
Row index
Array name
Fig. 7.13 Two-dimensional array with three rows and four columns.