chapter 7 - arraysmapaches.itz.edu.mx/~mbarajas/edinfo/arreglos_unidad_2.pdf · • en java, no se...

46
1 Arreglos Contenido Introducción Arreglos Declaración y dimensionamiento de arreglos Ejemplos de uso de arreglos Referencias y Parámetros de referencia Paso de arreglos a métodos Ordenamiento de arreglos Búsqueda en arreglos: Búsqueda Lineal y Binaria Arreglos Multidimensionado

Upload: others

Post on 31-Jul-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

1

Arreglos

Contenido

IntroducciónArreglosDeclaración y dimensionamiento de arreglosEjemplos de uso de arreglosReferencias y Parámetros de referenciaPaso de arreglos a métodos Ordenamiento de arreglosBúsqueda en arreglos: Búsqueda Lineal y BinariaArreglos Multidimensionado

Page 2: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

2

Introducción

• Arreglos– Estructuras de Datos– Contienen varios elementos relacionados del mismo tipo– Estáticos

• Conservan el mismo tamaño– Existen clases dinámicas tipo arreglo

• Pueden variar su tamaño

Page 3: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

3

Arreglos

• Arreglo– Grupo de localidades consecutivas de memoria– Mismo nombre y tipo

• Para referirse a un elemento, especificar– Nombre del Arreglo– Posición del Arreglo

• Formato: – nombrearreglo[posicion numero]– Primer elemento en la posición 0– El enésimo elemento del arreglo c: c[0], c[1]...c[n-1]

Indice

Page 4: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

4

Arreglos

c[6]

-45

6

0

72

1543

-89

0

62

-3

1

6453

78

Nombre del arreglo(Note que todos los elementos de estearreglo tienen el mismonombre, c)

c[0]

c[1]

c[2]

c[3]

c[11]

c[10]

c[9]

c[8]

c[7]

c[5]

c[4]

Número de posición de el elemento dentro del arreglo c

Page 5: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

5

Arreglos

• Arreglos– Todo arreglo sabe su propia longitudc.length

– Los elementos se usan como variables normalesc[ 0 ] = 3;c[ 0 ] += 5;

– Se pueden realizar operaciones en el indice• If x = 3,

c[ 5 - 2 ] == c[ 3 ] == c[ x ]

Page 6: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

6

Declaración y Dimensionamiento de Arreglos

• Declaración de Arreglos– Especificar el tipo, usar el operador new

• Dimensionar el número de elementos• En la declaración poner brackets después del nombre

– Dos pasos:int c[]; //declaracionc = new int[ 12 ]; //dimension

– Un paso:int c[] = new int[ 12 ];

– Los elementos primitivos son inicializados con cero o false• Las referencias no-primitivas son null

Page 7: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

7

Declaración y Dimensionamiento de Arreglos

• Declaraciones Múltiples

String b[] = new String[ 100 ], x[] = new String[ 27 ];

– Declaración de varios arreglos del mismo tipo• Los brackets se pueden poner despues del tipo de dato en vez

de ponerlos despues del nombredouble[] array1, array2;

• Arreglos– Pueden contener cualquier tipo de dato– Para tipos no-primitivos, todo elemento hace referencia a un

objeto

Page 8: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

8

Ejemplos del uso de arreglos

• new– Crea arreglos dinamicamente

• length– Longitud del arreglomiArreglo.length

• Listas Inicializadorasint miArreglo[] = { 1, 2, 3, 4, 5 };

• El operador new no es necesario, viene automaticamente• Inicializa un arreglo de 5 elementos enteros con los valores

mostrados

Page 9: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

9

Ver ejemplo de listas inicializadoras y length

Ver ejemplo de arreglo

Page 10: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

© 2000 Prentice Hall, Inc. All rights reserved.

Outline10

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

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 }

Notice how the initializer list is used (new not needed).

n.length is the length of the array. The length is one greater than the highest subscript.

Page 11: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

© 2000 Prentice Hall, Inc. All rights reserved.

Outline11

Program Output

Page 12: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

12

Ejemplos del uso de arreglos

• 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

Page 13: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

© 2000 Prentice Hall, Inc. All rights reserved.

Outline13

1. main

1.1 Initializefrequency array

2. Loop

2.1 Math.random

2.2 Update frequency

3. Display results

1 // Fig. 7.9: RollDie.java2 // Roll a six-sided die 6000 times3 import javax.swing.*;45 public class RollDie {6 public static void main( String args[] )7 {8 int face, frequency[] = new int[ 7 ];9 String output = "";1011 for ( int roll = 1; roll <= 6000; roll++ ) {12 face = 1 + ( int ) ( Math.random() * 6 );1313 ++frequency[ face ];14 }1516 output += "Face\tFrequency";1718 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 }

All elements start at zero (primitive data type). Increment proper location when die rolled.

Page 14: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

© 2000 Prentice Hall, Inc. All rights reserved.

Outline14

Program Output

Page 15: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

15

Referencias y Parámetros de Referencia

• Paso de argumentos a métodos– Llamada por valor: pasa una copia del argumento– Llamada por referencia: pasa el arguento original

• Mejora la eficiencia, debilita la seguridad

• En Java, no se puede seleccionar como pasar argumentos– Los tipos de datos primitivos pasan por valor– Las referencias a objetos pasan por referencia

• El objeto original puede ser modificado en el método– Los arreglos en Java se tratan como objetos

• Pasan por referencia

Page 16: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

16

• Paso de arreglos– Especificar el nombre del arreglo sin bracketsint miArreglo[ 24 ];miFuncion( miArreglo );

– Los arreglos pasan por referencia• Modifican las localidades de memoria originales

– El encabezado del método modificaArreglo puede servoid modificaArreglo( int b[] )

• Paso de los elementos del arreglo– Pasan por valor– Paso del nombre con su indice (i.e., miArreglo[3]) al

método

Referencias y Parámetros de Referencia

Page 17: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

© 2000 Prentice Hall, Inc. All rights reserved.

Outline17

1. init

1.1 GUI

1.2 Initialize array

2. modifyArray

1 // Fig. 7.10: PassArray.java2 // Passing arrays and individual array elements to methods3 import java.awt.Container;4 import javax.swing.*;56 public class PassArray extends JApplet {7 JTextArea outputArea;8 String output;910 public void init()11 {12 outputArea = new JTextArea();13 Container c = getContentPane();14 c.add( outputArea );1516 int a[] = { 1, 2, 3, 4, 5 };1718 output = "Effects of passing entire " +19 "array call-by-reference:\n" +20 "The values of the original array are:\n";2122 for ( int i = 0; i < a.length; i++ )23 output += " " + a[ i ];24

2525 modifyArray( a ); // array a passed call-by-reference2627 output += "\n\nThe values of the modified array are:\n";

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

Page 18: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

© 2000 Prentice Hall, Inc. All rights reserved.

Outline18

3. modifyElement

4. modifyArraydefinition

4.1 modifyElementdefinition

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.

Page 19: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

© 2000 Prentice Hall, Inc. All rights reserved.

Outline19

Program Output

Page 20: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

20

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

Page 21: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

21

7.7 Sorting Arrays

• ExampleOriginal: 3 4 2 6 7pass 1: 3 2 4 6 7pass 2: 2 3 4 6 7– Small elements "bubble" to the top

Page 22: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

© 2000 Prentice Hall, Inc. All rights reserved.

Outline22

1. init

1.1 GUI

1.2 Initialize array

2. bubbleSort

1 // Fig. 7.11: BubbleSort.java2 // This program sorts an array's values into3 // ascending order4 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 };1516 String output = "Data items in original order\n";1718 for ( int i = 0; i < a.length; i++ ) 19 output += " " + a[ i ];2021 bubbleSort( a );2223 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

Page 23: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

© 2000 Prentice Hall, Inc. All rights reserved.

Outline23

3. bubbleSortdefinition

4. swap definition

31 // sort the elements of an array with bubble sort

32 public void bubbleSort( int b[] )

33 {

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

Notice how the function takes an array and two elements as arguments.

Have b.length passes, each pass makes b.lengthcomparisons. If out of order, swap elements.

Use temporary holding area to swap elements.

Page 24: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

© 2000 Prentice Hall, Inc. All rights reserved.

Outline24

Program Output

Page 25: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

25

7.8 Searching Arrays: Linear Search andBinary 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

Page 26: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

26

7.8 Searching Arrays: Linear Search andBinary 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

Page 27: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

© 2000 Prentice Hall, Inc. All rights reserved.

Outline27

1. import

2. init

2.1 GUI

2.2 Register eventhandler

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

Page 28: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

© 2000 Prentice Hall, Inc. All rights reserved.

Outline28

2.3 Create and initializearray

3. linearSearchdefinition

4. Event handler

31

32 // create array and populate with even integers 0 to 198

33 a = new int[ 100 ];

3435 for ( int i = 0; i < a.length; i++ ) 36 a[ i ] = 2 * i;3738 }3940 // Search "array" for the specified "key" value4141 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;4647 return -1;48 }4950 public void actionPerformed( ActionEvent e )51 {52 String searchKey = e.getActionCommand();5354 // Array a is passed to linearSearch even though it55 // is an instance variable. Normally an array will56 // 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.

Page 29: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

© 2000 Prentice Hall, Inc. All rights reserved.

Outline29

4. Event handler

Program Output

60 if ( element != -1 )61 result.setText( "Found value in element " +62 element );63 else64 result.setText( "Value not found" );65 }66 }

Page 30: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

30

7.8 Searching Arrays: Linear Search andBinary 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 ) );

Page 31: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

© 2000 Prentice Hall, Inc. All rights reserved.

Outline31

1. import

1.1 Declare array a

2. init

2.1 GUI

2.2 Register eventhandler

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

Page 32: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

© 2000 Prentice Hall, Inc. All rights reserved.

Outline32

2.3 setFont

2.4 Create and initializearray

3. Event handler

3132 result = new JTextField( 22 );33 result.setEditable( false );34 c.add( result );3536 output = new JTextArea( 6, 60 );3737 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 }474849 public void actionPerformed( ActionEvent e )50 {51 String searchKey = e.getActionCommand();5253 // initialize display string for the new search54 display = "Portions of array searched\n";5556 // perform the binary search57 int element =58 binarySearch( a, Integer.parseInt( searchKey ) );5960 output.setText( display );

Set font for JTextArea.

Page 33: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

© 2000 Prentice Hall, Inc. All rights reserved.

Outline33

4. binarySearchdefinition

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.

Page 34: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

© 2000 Prentice Hall, Inc. All rights reserved.

Outline34

5. buildOutputdefinition

9192 return -1; // searchKey not found93 }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" );100101101 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 *

Page 35: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

© 2000 Prentice Hall, Inc. All rights reserved.

Outline35

Program Output

Page 36: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

36

Arreglos Multidimensionales

• Arreglos Multidimensionales– Representan tablas

• Formadas por m renglones y n columnas (arreglo m por n)• Pueden tener mas de dos indices

– Java no soporta indices multiples directamente• Crea un arreglo de arreglos como elementos• Arreglo de arreglos

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

Page 37: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

37

• Declaración– Renglones y columnas compuestos

tipoArreglo nombreArreglo[][] = newtipoArreglo[ numFilas ][numColumnas ];

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

– Listas InicializadorastipoArreglo nombreArreglo[][] = { {sub-lista renglon1 },

{sub-lista renglon2 }, ... };• int b[][] = { { 1, 2 }, { 3, 4 } };

1 2

3 4

Arreglos Multidimensionales

Page 38: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

38

• Renglones con diferentes columnas– Cada elemento de un renglón es un arregloint b[][];b = new int[ 2 ][ ]; // dimensiona renglonesb[ 0 ] = new int[ 5 ]; // dimensiona columnas

// para renglón 0b[ 1 ] = new int[ 3 ]; // dimensiona columnas

// para renglón 1

– Nótese como b[ 0 ] es inicializada como un nuevo arreglo int• Para pasar todo el renglón a una función, pasar b[ 0 ]

– b.length – número de renglones– b[ i ].length – número de columnas en el renglón i

Arreglos Multidimensionales

Page 39: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

© 2000 Prentice Hall, Inc. All rights reserved.

Outline39

1. init

1.1 GUI

1.2 Initialize double-scripted arrays

1 // Fig. 7.15: InitArray.java2 // Initializing multidimensional arrays3 import java.awt.Container;4 import javax.swing.*;56 public class InitArray extends JApplet {7 JTextArea outputArea;89 // paint the applet10 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 } }; 1819 outputArea.setText( "Values in array1 by row are\n" );20 buildOutput( array1 );2122 outputArea.append( "\nValues in array2 by row are\n" );23 buildOutput( array2 );24 }

Notice how the double scripted arrays are declared. Each row is inside braces.

Page 40: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

© 2000 Prentice Hall, Inc. All rights reserved.

Outline40

2. buildOutputdefinition

Program Output

2526 public void buildOutput( int a[][] )27 {28 for ( int i = 0; i < a.length; i++ ) {2930 for ( int j = 0; j < a[ i ].length; j++ ) 31 outputArea.append( a[ i ][ j ] + " " );3233 outputArea.append( "\n" );34 }35 }36 }

Page 41: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

41

Tarea 4

• Ejercicios de Ejemplos de Solución de Problemas:– Standalone para 1.1, 1.3, 1.6, 1.7, 1.10, 1.11, 1.23, 1.24, 1.4,

y 1.5, mostrando código con comentarios y ejemplo de corrida.

• Práctica No. VI y VIa (excepto ejercicio 3.0)

Page 42: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

42

7.9 Multiple-Subscripted Arrays

• Próximo applet– Use double scripted array for student grades

• Row - student• Column - grades on test

– Print average, high, low

Page 43: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

© 2000 Prentice Hall, Inc. All rights reserved.

Outline43

1. Initialize doublescripted 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 } };

1011 int students, exams;12 String output;13 JTextArea outputArea;1415 // initialize instance variables16 public void init()17 {18 students = grades.length;19 exams = grades[ 0 ].length;2021 outputArea = new JTextArea();22 Container c = getContentPane();23 c.add( outputArea );2425 // build the output string26 output = "The array is:\n";27 buildString();

Page 44: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

© 2000 Prentice Hall, Inc. All rights reserved.

Outline44

2.2 Create output

2.3 setFont

3. minimum definition

2829 output += "\n\nLowest grade: " + minimum() +30 "\nHighest grade: " + maximum() + "\n";3132 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

42 public int minimum()

43 {

44 int lowGrade = 100;

45

4646 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

Page 45: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

© 2000 Prentice Hall, Inc. All rights reserved.

Outline45

4. maximum definition

5. average definition

54 // find the maximum grade

55 public int maximum()

56 {

57 int highGrade = 0;

58

5959 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 }6667 // determine the average grade for a particular68 // student (or set of grades)69 public double average( int setOfGrades[] )70 {71 int total = 0;72

7373 for ( int i = 0; i < setOfGrades.length; i++ )74 total += setOfGrades[ i ];7576 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.

Page 46: Chapter 7 - Arraysmapaches.itz.edu.mx/~mbarajas/edinfo/Arreglos_unidad_2.pdf · • En Java, no se puede seleccionar como pasar argumentos – Los tipos de datos primitivos pasan

© 2000 Prentice Hall, Inc. All rights reserved.

Outline46

6. buildStringdefinition

79 // build output string80 public void buildString()81 {82 output += " "; // used to align column heads8384 for ( int i = 0; i < exams; i++ ) 85 output += "[" + i + "] ";8687 for ( int i = 0; i < students; i++ ) {88 output += "\ngrades[" + i + "] ";8990 for ( int j = 0; j < exams; j++ ) 91 output += grades[ i ][ j ] + " ";92 }93 }94 }