+ All Categories
Home > Documents > Chapter 7 - Arrays Outline 7.1Introduction 7.2Arrays 7.3Declaring and Allocating Arrays 7.4Examples...

Chapter 7 - Arrays Outline 7.1Introduction 7.2Arrays 7.3Declaring and Allocating Arrays 7.4Examples...

Date post: 19-Dec-2015
Category:
View: 225 times
Download: 1 times
Share this document with a friend
45
Chapter 7 - Arrays Outline 7.1 Introduction 7.2 Arrays 7.3 Declaring and Allocating 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 Multiple-Subscripted Arrays
Transcript

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

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

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

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

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 ]

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

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

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

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

11 // value for each element.

1212 int n[] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };

13

14 output += "Subscript\tValue\n";

15

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

17 output += i + "\t" + n[ i ] + "\n";

18

19 JTextArea outputArea = new JTextArea( 11, 10 );

20 outputArea.setText( output );

21

22 JOptionPane.showMessageDialog( null, outputArea,

23 "Initializing an Array with a Declaration",

24 JOptionPane.INFORMATION_MESSAGE );

25

26 System.exit( 0 );

27 }

28 }

Program Output

7.4 Examples Using Arrays

• Dice-rolling program– Use an array to keep track of which number was rolled

– 7 element array (subscripts 0 to 6)

– When a number is rolled, increment that array element

1. main

1.1 Initialize frequency array

2. Loop

2.1 Math.random

2.2 Update frequency

3. Display results

1 // Fig. 7.9: RollDie.java

2 // Roll a six-sided die 6000 times

3 import javax.swing.*;

4

5 public class RollDie {

6 public static void main( String args[] )

7 {

8 int face, frequency[] = new int[ 7 ];

9 String output = "";

10

11 for ( int roll = 1; roll <= 6000; roll++ ) {

12 face = 1 + ( int ) ( Math.random() * 6 );

1313 ++frequency[ face ];

14 }

15

16 output += "Face\tFrequency";

17

18 for ( face = 1; face < frequency.length; face++ )

19 output += "\n" + face + "\t" + frequency[ face ];

2021 JTextArea outputArea = new JTextArea( 7, 10 );22 outputArea.setText( output );2324 JOptionPane.showMessageDialog( null, outputArea,25 "Rolling a Die 6000 Times",26 JOptionPane.INFORMATION_MESSAGE );2728 System.exit( 0 );29 }30 }

Program Output

7.5 References and Reference Parameters

• Passing arguments to methods– Call-by-value: pass copy of argument

– Call-by-reference: pass original argument• Improves performance, weakens security

• In Java, cannot choose how to pass arguments– Primitive data types passed call-by-value

– References to objects passed call-by-reference• Original object can be changed in method

– Arrays in Java treated as objects• Passed call-by-reference

7.6 Passing Arrays to Functions

• Passing arrays– Specify array name without brackets int myArray[ 24 ];

myFunction( myArray );

– Arrays passed call-by-reference • Modifies original memory locations

– Header for method modifyArray might be

void modifyArray( int b[] )

• Passing array elements – Passed by call-by-value

– Pass subscripted name (i.e., myArray[3]) to method

1. init

1.1 GUI

1.2 Initialize array

2. modifyArray

1 // Fig. 7.10: PassArray.java

2 // Passing arrays and individual array elements to methods

3 import java.awt.Container;

4 import javax.swing.*;

5

6 public class PassArray extends JApplet {

7 JTextArea outputArea;

8 String output;

9

10 public void init()

11 {

12 outputArea = new JTextArea();

13 Container c = getContentPane();

14 c.add( outputArea );

15

16 int a[] = { 1, 2, 3, 4, 5 };

17

18 output = "Effects of passing entire " +

19 "array call-by-reference:\n" +

20 "The values of the original array are:\n";

21

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

23 output += " " + a[ i ];

24

2525 modifyArray( a ); // array a passed call-by-reference

26

27 output += "\n\nThe values of the modified array are:\n";

Arrays are passed call-by-reference, so modifyArray will alter the original array.

3. modifyElement

4. modifyArray definition

4.1 modifyElement definition

28

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

30 output += " " + a[ i ];

31

32 output += "\n\nEffects of passing array " +

33 "element call-by-value:\n" +

34 "a[3] before modifyElement: " + a[ 3 ];

35

3636 modifyElement( a[ 3 ] );

37

38 output += "\na[3] after modifyElement: " + a[ 3 ];

39 outputArea.setText( output );

40 }

41

42 public void modifyArray( int b[] )

43 {

44 for ( int j = 0; j < b.length; j++ )

45 b[ j ] *= 2;

46 }

47

48 public void modifyElement( int e )

49 {

50 e *= 2;

51 }

52 }

Individual elements passed call-by-value, so only a copy is modified.

Program Output

7.7 Sorting Arrays

• Sorting data– Important computing application

– Virtually every organization must sort some data • Massive amounts must be sorted

• Bubble sort (sinking sort) – Several passes through the array – Successive pairs of elements are compared

• If increasing order (or identical ), no change

• If decreasing order, elements exchanged

– Repeat

– Easy to program, but runs slowly

7.7 Sorting Arrays

• ExampleOriginal: 3 4 2 6 7

pass 1: 3 2 4 6 7

pass 2: 2 3 4 6 7

– Small elements "bubble" to the top

1. init

1.1 GUI

1.2 Initialize array

2. bubbleSort

1 // Fig. 7.11: BubbleSort.java

2 // This program sorts an array's values into3 // ascending order

4 import java.awt.*;

5 import javax.swing.*;67 public class BubbleSort extends JApplet {8 public void init()

9 {

10 JTextArea outputArea = new JTextArea();11 Container c = getContentPane();

12 c.add( outputArea );

1314 int a[] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };

15

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

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 }

Program Output

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

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

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 );

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

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 }

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 ) );

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 );

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 );

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.

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 *

Program Output

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

7.9 Multiple-Subscripted Arrays

• Declaration– Fixed rows and columns

arrayType arrayName[][] = new arrayType[ numRows ][numColumns ];

• int b[][] = new int[ 3 ][ 3 ];

– Initializer listsarrayType arrayName[][] = { {row1 sub-list}, {row2 sub-list}, ... };

• int b[][] = { { 1, 2 }, { 3, 4 } };

1 2

3 4

7.9 Multiple-Subscripted Arrays

• 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

1. init

1.1 GUI

1.2 Initialize double-scripted arrays

1 // Fig. 7.15: InitArray.java

2 // Initializing multidimensional arrays

3 import java.awt.Container;

4 import javax.swing.*;

5

6 public class InitArray extends JApplet {

7 JTextArea outputArea;

8

9 // paint the applet

10 public void init()

11 {

12 outputArea = new JTextArea();

13 Container c = getContentPane();

14 c.add( outputArea );

15

1616 int array1[][] = { { 1, 2, 3 }, { 4, 5, 6 } };

17 int array2[][] = { { 1, 2 }, { 3 }, { 4, 5, 6 } };

18

19 outputArea.setText( "Values in array1 by row are\n" );

20 buildOutput( array1 );

21

22 outputArea.append( "\nValues in array2 by row are\n" );

23 buildOutput( array2 );

24 }

2. buildOutput definition

Program Output

25

26 public void buildOutput( int a[][] )

27 {

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

29

30 for ( int j = 0; j < a[ i ].length; j++ )

31 outputArea.append( a[ i ][ j ] + " " );

32

33 outputArea.append( "\n" );34 }35 }36 }

7.9 Multiple-Subscripted Arrays

• Upcoming applet– Use double scripted array for student grades

• Row - student

• Column - grades on test

– Print average, high, low

1. Initialize double scripted array

2. init

2.1 GUI

1 // Fig. 7.16: DoubleArray.java

2 // Double-subscripted array example

3 import java.awt.*;

4 import javax.swing.*;

5

6 public class DoubleArray extends JApplet {

7 int grades[][] = { { 77, 68, 86, 73 },

8 { 96, 87, 89, 81 },

9 { 70, 90, 86, 81 } };

10

11 int students, exams;

12 String output;

13 JTextArea outputArea;

14

15 // initialize instance variables

16 public void init()

17 {

18 students = grades.length;

19 exams = grades[ 0 ].length;

20

21 outputArea = new JTextArea();

22 Container c = getContentPane();

23 c.add( outputArea );

24

25 // build the output string

26 output = "The array is:\n";

27 buildString();

2.2 Create output

2.3 setFont

3. minimum definition

28

29 output += "\n\nLowest grade: " + minimum() +

30 "\nHighest grade: " + maximum() + "\n";

31

32 for ( int i = 0; i < students; i++ )

33 output += "\nAverage for student " + i + " is " +

3434 average( grades[ i ] );

35

36 outputArea.setFont(

37 new Font( "Courier", Font.PLAIN, 12 ) );

38 outputArea.setText( output );

39 }

40

41 // find the minimum grade

4242 public int minimum()

43 {

44 int lowGrade = 100;

45

46 for ( int i = 0; i < students; i++ )

47 for ( int j = 0; j < exams; j++ )

48 if ( grades[ i ][ j ] < lowGrade )

49 lowGrade = grades[ i ][ j ];

50

51 return lowGrade;

52 }

53

Look through entire array. If a grade is lower than lowGrade, lowGrade is set to it.

Pass a row (a student) to method average

4. maximum definition

5. average definition

54 // find the maximum grade

5555 public int maximum()

56 {

57 int highGrade = 0;

58

59 for ( int i = 0; i < students; i++ )

60 for ( int j = 0; j < exams; j++ )

61 if ( grades[ i ][ j ] > highGrade )

62 highGrade = grades[ i ][ j ];

63

64 return highGrade;

65 }

66

67 // determine the average grade for a particular

68 // student (or set of grades)

69 public double average( int setOfGrades[] )

70 {

71 int total = 0;

72

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

74 total += setOfGrades[ i ];

75

76 return ( double ) total / setOfGrades.length;

77 }

78

Like minimum, searches through array, sets highGrade.

Rows of the double scripted array are actually arrays containing the grades.

6. buildString definition

79 // build output string

80 public void buildString()

81 {

82 output += " "; // used to align column heads

83

84 for ( int i = 0; i < exams; i++ )

85 output += "[" + i + "] ";

86

87 for ( int i = 0; i < students; i++ ) {

88 output += "\ngrades[" + i + "] ";

89

90 for ( int j = 0; j < exams; j++ )

91 output += grades[ i ][ j ] + " ";

92 }

93 }

94 }

The array is:

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

grades[0] 77 68 86 73

grades[1] 96 87 89 81

grades[2] 70 90 86 81

Lowest grade: 68

Highest grade: 96

Average for student 0 is 76.0

Average for student 1 is 88.25

Average for student 2 is 81.75


Recommended