This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
2000 Prentice Hall, Inc. All rights reserved.
1
Chapter 7 - Arrays
Outline7.1 Introduction7.2 Arrays7.3 Declaring and Allocating Arrays7.4 Examples Using Arrays7.5 References and Reference Parameters7.6 Passing Arrays to Methods7.7 Sorting Arrays7.8 Searching Arrays: Linear Search and Binary Search7.9 Multiple-Subscripted Arrays
2000 Prentice Hall, Inc. All rights reserved.
2
7.1 Introduction
• Arrays– Data structures
– Contain several related items of same type
– Static• Remain same size
– In later chapters, discuss dynamic array-like classes• Can grow and shrink
2000 Prentice Hall, Inc. All rights reserved.
3
7.2 Arrays
• Array– Group of consecutive memory locations
– Same name and type
• To refer to an element, specify– Array name
– Position number
• Format: – arrayname[position number]– First element at position 0
– n element array named c: c[0], c[1]...c[n-1]
Subscript
2000 Prentice Hall, Inc. All rights reserved.
4
7.2 Arrays
c[6]
-45
6
0
72
1543
-89
0
62
-3
1
6453
78
Name of array (Note that all elements of this array have the same name, c)
c[0]
c[1]
c[2]
c[3]
c[11]
c[10]
c[9]
c[8]
c[7]
c[5]
c[4]
Position number of the element within array c
2000 Prentice Hall, Inc. All rights reserved.
5
7.2 Arrays
• Arrays– Every array knows its own length
c.length– Elements are like normal variables
c[ 0 ] = 3;
c[ 0 ] += 5;– Can perform operations in subscript
• If x = 3,
c[ 5 - 2 ] == c[ 3 ] == c[ x ]
2000 Prentice Hall, Inc. All rights reserved.
6
7.3 Declaring and Allocating Arrays
• Declaring arrays– Specify type, use new operator
• Allocate number of elements
• Place brackets after name in declaration
– Two steps:int c[]; //declaration
c = new int[ 12 ]; //allocation
– One step:int c[] = new int[ 12 ];
– Primitive elements initialized to zero or false• Non-primitive references are null
2000 Prentice Hall, Inc. All rights reserved.
7
7.3 Declaring and Allocating Arrays
• Multiple declarations
String b[] = new String[ 100 ],
x[] = new String[ 27 ];
– Declaring multiple arrays of same type• Can put brackets after data type instead of after name
double[] array1, array2;
• Arrays– Can contain any data type
– For non-primitive types, every element a reference to an object
2000 Prentice Hall, Inc. All rights reserved.
8
7.4 Examples Using Arrays
• new– Dynamically creates arrays
• length– Length of the array
myArray.length
• Initializer listsint myArray[] = { 1, 2, 3, 4, 5 }; • new operator not needed, provided automatically
• Initializes 5 element integer array with values shown
2000 Prentice Hall, Inc. All rights reserved.
Outline9
1. main
1.1 Initializer list
2. Loop
3. GUI
1 // Fig. 7.4: InitArray.java
2 // initializing an array with a declaration
3 import javax.swing.*;
4
5 public class InitArray {
6 public static void main( String args[] )
7 {
8 String output = "";
9
10 // Initializer list specifies number of elements and
16 String output = "Data items in original order\n";1718 for ( int i = 0; i < a.length; i++ ) 19 output += " " + a[ i ];
20
21 bubbleSort( a );22
23 output += "\n\nData items in ascending order\n";
2425 for ( int i = 0; i < a.length; i++ )
26 output += " " + a[ i ];
2728 outputArea.setText( output );29 }30
2000 Prentice Hall, Inc. All rights reserved.
Outline22
3. bubbleSort definition
4. swap definition
31 // sort the elements of an array with bubble sort
3232 public void bubbleSort( int b[] )
33 {
34 for ( int pass = 1; pass < b.length; pass++ ) // passes
35 for ( int i = 0; i < b.length - 1; i++ ) // one pass
36 if ( b[ i ] > b[ i + 1 ] ) // one comparison
37 swap( b, i, i + 1 ); // one swap
38 }
39
40 // swap two elements of an array
4141 public void swap( int c[], int first, int second )
42 {
43 int hold; // temporary holding area for swap
44
4545 hold = c[ first ];
46 c[ first ] = c[ second ];
47 c[ second ] = hold;
48 }
49 }
Have b.length passes, each pass makes b.length comparisons. If out of order, swap elements.
Use temporary holding area to swap elements.
Notice how the function takes an array and two elements as arguments.
2000 Prentice Hall, Inc. All rights reserved.
Outline23
Program Output
2000 Prentice Hall, Inc. All rights reserved.
24
7.8 Searching Arrays: Linear Search and Binary Search
• Search an array for a key value
• Linear search– Simple
– Compare each element of array with key value
– Useful for small and unsorted arrays
2000 Prentice Hall, Inc. All rights reserved.
25
7.8 Searching Arrays: Linear Search and Binary Search
• Binary search – For sorted arrays
– Compares middle element with key• If equal, match found
• If key < middle, looks in first half of array
• If key > middle, looks in last half
• Repeat
– Very fast, at most n steps, where 2 > number of elements• 30 element array takes at most 5 steps
2 > 30
n
5
2000 Prentice Hall, Inc. All rights reserved.
Outline26
1. import
2. init
2.1 GUI
2.2 Register event handler
1 // Fig. 7.12: LinearSearch.java2 // Linear search of an array3 import java.awt.*;4 import java.awt.event.*;5 import javax.swing.*;67 public class LinearSearch extends JApplet8 implements ActionListener {9 JLabel enterLabel, resultLabel;10 JTextField enter, result;11 int a[];1213 public void init()14 {15 Container c = getContentPane();16 c.setLayout( new FlowLayout() );1718 enterLabel = new JLabel( "Enter integer search key" );19 c.add( enterLabel );2021 enter = new JTextField( 10 );22 enter.addActionListener( this );23 c.add( enter );2425 resultLabel = new JLabel( "Result" );26 c.add( resultLabel );2728 result = new JTextField( 20 );29 result.setEditable( false );30 c.add( result );
2000 Prentice Hall, Inc. All rights reserved.
Outline27
2.3 Create and initialize array
3. linearSearch definition
4. Event handler
31
32 // create array and populate with even integers 0 to 198
33 a = new int[ 100 ];
34
35 for ( int i = 0; i < a.length; i++ )
36 a[ i ] = 2 * i;
37
38 }
39
40 // Search "array" for the specified "key" value
4141 public int linearSearch( int array[], int key )
42 {
43 for ( int n = 0; n < a.length; n++ )
44 if ( array[ n ] == key )
45 return n;
46
47 return -1;
48 }
49
50 public void actionPerformed( ActionEvent e )
51 {
52 String searchKey = e.getActionCommand();
5354 // Array a is passed to linearSearch even though it
55 // is an instance variable. Normally an array will
56 // be passed to a method for searching.
57 int element =
58 linearSearch( a, Integer.parseInt( searchKey ) );
59
Linear searching compares each element to the key value.
2000 Prentice Hall, Inc. All rights reserved.
Outline28
4. Event handler
Program Output
60 if ( element != -1 )
61 result.setText( "Found value in element " +
62 element );
63 else
64 result.setText( "Value not found" );
65 }
66 }
2000 Prentice Hall, Inc. All rights reserved.
29
7.8 Searching Arrays: Linear Search and Binary Search
– Sets output to use courier, a fixed-width font• Helps to align display
– Method setFont• Can change font of most GUI components
• Takes a Font object
– Font objects• Initialized with
– String name of font– int representing style (Font.PLAIN, Font.BOLD, Font.ITALIC)
– int representing point size
36 output = new JTextArea( 6, 60 );37 output.setFont(38 new Font( "Courier", Font.PLAIN, 12 ) );
2000 Prentice Hall, Inc. All rights reserved.
Outline30
1. import
1.1 Declare array a
2. init
2.1 GUI
2.2 Register event handler
1 // Fig. 7.13: BinarySearch.java2 // Binary search of an array3 import java.awt.*;4 import java.awt.event.*;5 import javax.swing.*;6 import java.text.*;78 public class BinarySearch extends JApplet9 implements ActionListener {10 JLabel enterLabel, resultLabel;11 JTextField enter, result;12 JTextArea output;1314 int a[];15 String display = "";1617 public void init()18 {19 Container c = getContentPane();20 c.setLayout( new FlowLayout() );2122 enterLabel = new JLabel( "Enter key" );23 c.add( enterLabel );2425 enter = new JTextField( 5 );26 enter.addActionListener( this );27 c.add( enter );2829 resultLabel = new JLabel( "Result" );30 c.add( resultLabel );
2000 Prentice Hall, Inc. All rights reserved.
Outline31
2.3 setFont
2.4 Create and initialize array
3. Event handler
3132 result = new JTextField( 22 );33 result.setEditable( false );34 c.add( result );3536 output = new JTextArea( 6, 60 );37 output.setFont(38 new Font( "Courier", Font.PLAIN, 12 ) );39 c.add( output );4041 // create array and fill with even integers 0 to 2842 a = new int[ 15 ];4344 for ( int i = 0; i < a.length; i++ ) 45 a[ i ] = 2 * i;46 }4748
49 public void actionPerformed( ActionEvent e )
50 {
51 String searchKey = e.getActionCommand();
52
53 // initialize display string for the new search
54 display = "Portions of array searched\n";
55
56 // perform the binary search
57 int element =
58 binarySearch( a, Integer.parseInt( searchKey ) );
59
60 output.setText( display );
2000 Prentice Hall, Inc. All rights reserved.
Outline32
4. binarySearch definition
4.1 Initialize subscripts
61
62 if ( element != -1 )
63 result.setText(
64 "Found value in element " + element );
65 else
66 result.setText( "Value not found" );
67 }6869 // Binary search70 public int binarySearch( int array[], int key ) 71 {72 int low = 0; // low subscript73 int high = array.length - 1; // high subscript74 int middle; // middle subscript7576 while ( low <= high ) {77 middle = ( low + high ) / 2;7879 // The following line is used to display the part80 // of the array currently being manipulated during81 // each iteration of the binary search loop.82 buildOutput( low, middle, high ); 838484 if ( key == array[ middle ] ) // match85 return middle;86 else if ( key < array[ middle ] )87 high = middle - 1; // search low end of array88 else89 low = middle + 1; // search high end of array90 }
Middle element is the average of the high and low elements.
If key equal to middle element, return it. If less or greater, adjust high or low.
2000 Prentice Hall, Inc. All rights reserved.
Outline33
5. buildOutput definition
9192 return -1; // searchKey not found
93 }9495 // Build one row of output showing the current96 // part of the array being processed.97 void buildOutput( int low, int mid, int high )98 {99 DecimalFormat twoDigits = new DecimalFormat( "00" );100
101101 for ( int i = 0; i < a.length; i++ ) {
102 if ( i < low || i > high )
103 display += " ";
104 else if ( i == mid ) // mark middle element in output
105 display += twoDigits.format( a[ i ] ) + "* ";
106 else
107 display += twoDigits.format( a[ i ] ) + " ";
108 }
109
110 display += "\n";
111 }
112}
Loop through and display part of array being searched. If not being searched, display a blank. Mark middle element with *
2000 Prentice Hall, Inc. All rights reserved.
Outline34
Program Output
2000 Prentice Hall, Inc. All rights reserved.
35
7.9 Multiple-Subscripted Arrays
• Multiple-Subscripted Arrays– Represent tables
• Arranged by m rows and n columns (m by n array)
• Can have more than two subscripts
– Java does not support multiple subscripts directly• Creates an array with arrays as its elements
• Array of arrays
Row 0
Row 1
Row 2
Column 0 Column 1 Column 2 Column 3a[0][0]
a[1][0]
a[2][0]
a[0][1]
a[1][1]
a[2][1]
a[0][2]
a[1][2]
a[2][2]
a[0][3]
a[1][3]
a[2][3]
Row subscript
Array name
Column subscript
2000 Prentice Hall, Inc. All rights reserved.
36
7.9 Multiple-Subscripted Arrays
• Declaration– Fixed rows and columns
arrayType arrayName[][] = new arrayType[ numRows ][numColumns ];
• Rows with different columns– Each row element is an arrayint b[][];b = new int[ 2 ][ ]; // allocate rowsb[ 0 ] = new int[ 5 ]; // allocate columns for
// row 0b[ 1 ] = new int[ 3 ]; // allocate columns for
// row 1
– Notice how b[ 0 ] is initialized as a new int array• To pass the entire row to a function, pass b[ 0 ]
– b.length - number of rows– b[ i ].length - number of columns in row i