Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 7 - Arrays Outline 7.1Introduction 7.2Arrays 7.3Declaring and Allocating Arrays 7.4Examples Using Arrays 7.5References and Reference Parameters.

Similar presentations


Presentation on theme: "Chapter 7 - Arrays Outline 7.1Introduction 7.2Arrays 7.3Declaring and Allocating Arrays 7.4Examples Using Arrays 7.5References and Reference Parameters."— Presentation transcript:

1 Chapter 7 - Arrays Outline 7.1Introduction 7.2Arrays 7.3Declaring and Allocating Arrays 7.4Examples Using Arrays 7.5References and Reference Parameters 7.6Passing Arrays to Methods 7.7Sorting Arrays 7.8Searching Arrays: Linear Search and Binary Search 7.9Multiple-Subscripted Arrays

2 7.1Introduction 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

3 7.2Arrays 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

4 7.2Arrays 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

5 7.2Arrays 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 ]

6 7.3Declaring 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 7.3Declaring 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

8 7.4Examples Using Arrays new –Dynamically creates arrays length –Length of the array myArray.length Initializer lists int myArray[] = { 1, 2, 3, 4, 5 }; new operator not needed, provided automatically Initializes 5 element integer array with values shown

9 1// Fig. 7.4: InitArray.java 2// initializing an array with a declaration 3import javax.swing.*; 4 5public 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. 12 12 int n[] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; 13 14 output += "Subscript\tValue\n"; 15 16 16 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}

10 Program Output

11 7.4Examples 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

12 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 3import javax.swing.*; 4 5public 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 ); 13 13 ++frequency[ face ]; 14 } 15 16 output += "Face\tFrequency"; 17 18 for ( face = 1; face < frequency.length; face++ ) 19 output += "\n" + face + "\t" + frequency[ face ]; 20 21 JTextArea outputArea = new JTextArea( 7, 10 ); 22 outputArea.setText( output ); 23 24 JOptionPane.showMessageDialog( null, outputArea, 25 "Rolling a Die 6000 Times", 26 JOptionPane.INFORMATION_MESSAGE ); 27 28 System.exit( 0 ); 29 } 30}

13 Program Output

14 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

15 7.6Passing 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

16 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 3import java.awt.Container; 4import javax.swing.*; 5 6public 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 25 25 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.

17 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 36 36 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.

18 Program Output

19 7.7Sorting 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

20 7.7Sorting Arrays Example Original: 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

21 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 into 3// ascending order 4import java.awt.*; 5import javax.swing.*; 6 7public class BubbleSort extends JApplet { 8 public void init() 9 { 10 JTextArea outputArea = new JTextArea(); 11 Container c = getContentPane(); 12 c.add( outputArea ); 13 14 int a[] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; 15 16 String output = "Data items in original order\n"; 17 18 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"; 24 25 for ( int i = 0; i < a.length; i++ ) 26 output += " " + a[ i ]; 27 28 outputArea.setText( output ); 29 } 30

22 3. bubbleSort definition 4. swap definition 31 // sort the elements of an array with bubble sort 32 32 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 41 41 public void swap( int c[], int first, int second ) 42 { 43 int hold; // temporary holding area for swap 44 45 45 hold = c[ first ]; 46 c[ first ] = c[ second ]; 47 c[ second ] = hold; 48 } 49}

23 Program Output

24 7.8Searching 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

25 7.8Searching 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

26 1. import 2. init 2.1 GUI 2.2 Register event handler 1// Fig. 7.12: LinearSearch.java 2// Linear search of an array 3import java.awt.*; 4import java.awt.event.*; 5import javax.swing.*; 6 7public class LinearSearch extends JApplet 8 implements ActionListener { 9 JLabel enterLabel, resultLabel; 10 JTextField enter, result; 11 int a[]; 12 13 public void init() 14 { 15 Container c = getContentPane(); 16 c.setLayout( new FlowLayout() ); 17 18 enterLabel = new JLabel( "Enter integer search key" ); 19 c.add( enterLabel ); 20 21 enter = new JTextField( 10 ); 22 enter.addActionListener( this ); 23 c.add( enter ); 24 25 resultLabel = new JLabel( "Result" ); 26 c.add( resultLabel ); 27 28 result = new JTextField( 20 ); 29 result.setEditable( false ); 30 c.add( result );

27 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 41 41 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(); 53 54 // 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

28 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}

29 7.8Searching 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 ) );

30 1. import 1.1 Declare array a 2. init 2.1 GUI 2.2 Register event handler 1// Fig. 7.13: BinarySearch.java 2// Binary search of an array 3import java.awt.*; 4import java.awt.event.*; 5import javax.swing.*; 6import java.text.*; 7 8public class BinarySearch extends JApplet 9 implements ActionListener { 10 JLabel enterLabel, resultLabel; 11 JTextField enter, result; 12 JTextArea output; 13 14 int a[]; 15 String display = ""; 16 17 public void init() 18 { 19 Container c = getContentPane(); 20 c.setLayout( new FlowLayout() ); 21 22 enterLabel = new JLabel( "Enter key" ); 23 c.add( enterLabel ); 24 25 enter = new JTextField( 5 ); 26 enter.addActionListener( this ); 27 c.add( enter ); 28 29 resultLabel = new JLabel( "Result" ); 30 c.add( resultLabel );

31 2.3 setFont 2.4 Create and initialize array 3. Event handler 31 32 result = new JTextField( 22 ); 33 result.setEditable( false ); 34 c.add( result ); 35 36 output = new JTextArea( 6, 60 ); 37 output.setFont( 38 new Font( "Courier", Font.PLAIN, 12 ) ); 39 c.add( output ); 40 41 // create array and fill with even integers 0 to 28 42 a = new int[ 15 ]; 43 44 for ( int i = 0; i < a.length; i++ ) 45 a[ i ] = 2 * i; 46 } 47 48 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 );

32 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 } 68 69 // Binary search 70 public int binarySearch( int array[], int key ) 71 { 72 int low = 0; // low subscript 73 int high = array.length - 1; // high subscript 74 int middle; // middle subscript 75 76 while ( low <= high ) { 77 middle = ( low + high ) / 2; 78 79 // The following line is used to display the part 80 // of the array currently being manipulated during 81 // each iteration of the binary search loop. 82 buildOutput( low, middle, high ); 83 84 84 if ( key == array[ middle ] ) // match 85 return middle; 86 else if ( key < array[ middle ] ) 87 high = middle - 1; // search low end of array 88 else 89 low = middle + 1; // search high end of array 90 } 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.

33 5. buildOutput definition 91 92 return -1; // searchKey not found 93 } 94 95 // Build one row of output showing the current 96 // part of the array being processed. 97 void buildOutput( int low, int mid, int high ) 98 { 99 DecimalFormat twoDigits = new DecimalFormat( "00" ); 100 101 101 for ( int i = 0; i < a.length; i++ ) { 102 if ( 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 *

34 Program Output

35 7.9Multiple-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 0Column 1Column 2Column 3 a[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

36 7.9Multiple-Subscripted Arrays Declaration –Fixed rows and columns arrayType arrayName [][] = new arrayType [ numRows ][ numColumns ]; int b[][] = new int[ 3 ][ 3 ]; –Initializer lists arrayType arrayName [][] = { { row1 sub-list }, { row2 sub-list },... }; int b[][] = { { 1, 2 }, { 3, 4 } }; 12 34

37 7.9Multiple-Subscripted Arrays Rows with different columns –Each row element is an array int b[][]; b = new int[ 2 ][ ]; // allocate rows b[ 0 ] = new int[ 5 ]; // allocate columns for // row 0 b[ 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

38 1. init 1.1 GUI 1.2 Initialize double- scripted arrays 1// Fig. 7.15: InitArray.java 2// Initializing multidimensional arrays 3import java.awt.Container; 4import javax.swing.*; 5 6public 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 16 16 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 }

39 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}

40 7.9Multiple-Subscripted Arrays Upcoming applet –Use double scripted array for student grades Row - student Column - grades on test –Print average, high, low

41 1. Initialize double scripted array 2. init 2.1 GUI 1// Fig. 7.16: DoubleArray.java 2// Double-subscripted array example 3import java.awt.*; 4import javax.swing.*; 5 6public 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();

42 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 " + 34 34 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 42 42 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

43 4. maximum definition 5. average definition 54 // find the maximum grade 55 55 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.

44 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}

45 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


Download ppt "Chapter 7 - Arrays Outline 7.1Introduction 7.2Arrays 7.3Declaring and Allocating Arrays 7.4Examples Using Arrays 7.5References and Reference Parameters."

Similar presentations


Ads by Google