Chapter 9 Arrays Java Programming From Problem Analysis

Chapter 9: Arrays Java Programming: From Problem Analysis to Program Design, Second Edition

Chapter Objectives s Learn about arrays. s Explore how to declare and manipulate data into arrays. s Understand the meaning of “array index out of bounds. ” s Become familiar with the restrictions on array processing. 2

Chapter Objectives s Discover how to pass an array as a parameter to a method. s Discover how to manipulate data in a twodimensional array. s Learn about multidimensional arrays. 3

Enter 5 numbers: Motivation 3 6 8 9 0 = 26 sum and print them in reverse order. Write a program to read 5 numbers, Sum find their Numbers is reverse = 0 9 8 6 3 import java. util. *; public class Rev. Order{ static Scanner console = new Scanner(System. in); public static void main(String[] args){ int item 0, item 1, item 2, item 3, item 4; int sum; System. out. println("Enter 5 numbers: "); item 0=console. next. Int(); item 1=console. next. Int(); item 2=console. next. Int(); item 3=console. next. Int(); item 4=console. next. Int(); sum = item 0+item 1+item 2+item 3+item 4; System. out. println("Sum = " + sum); System. out. print("Numbers is reverse = "); System. out. println(item 4+" "+item 3+" "+item 2+" "+item 1+" "+item 0); } } 4

Motivation Write a program to read 100 numbers, find their sum and print them in reverse order ? ? ? 5

Motivation s Note the following in the preceding program: s 5 variables must be declared. s All variables are of type int. s Variables name (num 0 num 4); s Instead of having to use a large number of individual and unconnected variables, we can use a single data structure that combines them. 6

Motivation s In this chapter, we will examine: s How to store collections of items and access these items using one variable name given to the collection. s The data structure that lets you do all of theses things in java is called array. 7

Array s A structured data type with a fixed number of components. s Every component is of the same type. s Components are accessed using their relative positions in the array. 8
![One-Dimensional Arrays s Syntax to declare an array: sdata. Type[ ] array. Name; s One-Dimensional Arrays s Syntax to declare an array: sdata. Type[ ] array. Name; s](http://slidetodoc.com/presentation_image_h2/8641a476ffdb66a49cf4b22c91963709/image-9.jpg)
One-Dimensional Arrays s Syntax to declare an array: sdata. Type[ ] array. Name; s In java, an array is an object: s It is a reference variable. s To store data we must instantiate the array object using new operator. s Syntax to instantiate an array object: array. Name = new data. Type[int. Exp] Where int. Exp = number of components in array >= 0 9
![One-Dimensional Arrays s Declaration with instantiation: data. Type[ ] array. Name = new data. One-Dimensional Arrays s Declaration with instantiation: data. Type[ ] array. Name = new data.](http://slidetodoc.com/presentation_image_h2/8641a476ffdb66a49cf4b22c91963709/image-10.jpg)
One-Dimensional Arrays s Declaration with instantiation: data. Type[ ] array. Name = new data. Type[int. Exp] s Declaring more than one array of the same type: data. Type[ ] array. Name 1, array. Name 2; s Syntax to access an array component: s array. Name[index. Exp] s int. Exp = number of components in array >= 0 s 0 <= index. Exp <= int. Exp 10
![Array num Example 9 -1 s The statement: int[] num = new int[5]; s Array num Example 9 -1 s The statement: int[] num = new int[5]; s](http://slidetodoc.com/presentation_image_h2/8641a476ffdb66a49cf4b22c91963709/image-11.jpg)
Array num Example 9 -1 s The statement: int[] num = new int[5]; s Declares and creates the array num of 5 components. s Each component is of type int. s The components are accessed as: num[0], num[1], num[2], num[3], num[4] 11
![Array num int[] num = new int[5]; Why all the values = 0 ? Array num int[] num = new int[5]; Why all the values = 0 ?](http://slidetodoc.com/presentation_image_h2/8641a476ffdb66a49cf4b22c91963709/image-12.jpg)
Array num int[] num = new int[5]; Why all the values = 0 ? ? ? 12

Array num s When an array is instantiated. Java automatically initializes its components to their default values. For example, numeric arrays are initialized to 0. s What are string, char array initialized to? 13
![Alternate Ways to Declare an array s int list[]; // here [] is after Alternate Ways to Declare an array s int list[]; // here [] is after](http://slidetodoc.com/presentation_image_h2/8641a476ffdb66a49cf4b22c91963709/image-14.jpg)
Alternate Ways to Declare an array s int list[]; // here [] is after list not int s But take care, what is the difference here: s int alpha[], beta; s int[] gamma, delta; s It is recommended that you declare arrays as int[]. 14
![Array list int [] list = new int[10]; 15 Array list int [] list = new int[10]; 15](http://slidetodoc.com/presentation_image_h2/8641a476ffdb66a49cf4b22c91963709/image-15.jpg)
Array list int [] list = new int[10]; 15

Array list 16

Specifying Array Size During Program Execution int array. Size; System. out. print("Enter the size of the array: "); array. Size = console. next. Int(); System. out. println(); int[] list = new int[array. Size]; s Arrays that are created during program execution are called dynamic arrays. 17
![Array Initialization During Declaration double[] sales = {12. 25, 32. 50, 16. 90, 23, Array Initialization During Declaration double[] sales = {12. 25, 32. 50, 16. 90, 23,](http://slidetodoc.com/presentation_image_h2/8641a476ffdb66a49cf4b22c91963709/image-18.jpg)
Array Initialization During Declaration double[] sales = {12. 25, 32. 50, 16. 90, 23, 45. 68}; s The values, called initial values, are placed between braces and separated by commas. s Here, sales[0]= 12. 25, sales[1]= 32. 50, sales[2]= 16. 90, sales[3]= 23. 00, and sales[4]= 45. 68. s When declaring and initializing arrays, the size of the array is determined by the number of initial values within the braces. s If an array is declared and initialized simultaneously, we do not use the operator new to instantiate the array object. 18

Arrays and the Instance Variable length s A public instance variable length is associated with each array that has been instantiated. s The variable length contains the size of the array. s The variable length can be directly accessed in a program using the array name and the dot operator. s This statement creates the array list of six components and initializes the components using the values given. int[] list = {10, 20, 30, 40, 50, 60}; Here, list. length is 6. 19

Arrays and the Instance Variable length s This statement creates the array num. List of 10 components and initializes each component to 0. int[] num. List = new int[10]; s The value of num. List. length is 10. s These statements store 5, 10, 15, and 20, respectively, in the first four components of num. List[0] num. List[1] num. List[2] num. List[3] = = 5; 10; 15; 20; s The value of num. List. length is still 10. s You can store the number of filled elements, that is, the actual number of elements, in the array in a variable, SAYno. Of. Element. It is a common practice for a program to keep track of the number of filled elements in an array. 20

Processing One-Dimensional Arrays s Loops used to step through elements in array and perform operations. int[] list = new int[100]; int i; //process list[i], the (i + 1)th element of list for (i = 0; i < list. length; i++) //inputting data to list for (i = 0; i < list. length; i++) list[i] = console. next. Int(); //outputting data from list for (i = 0; i < list. length; i++) System. out. print(list[i] + " "); s Remember to start loop counter from 0 because Array index starts from 0. 21

Arrays s Some operations on arrays: s s Initialize Input data Output stored data Find largest/smallest/sum/average of elements Example 9_3 double[] sales = new double[10]; int index; double largest. Sale, sum, average; 22

Code to Initialize Array to Specific Value (10. 00) for (index = 0; index < sales. length; index++) sales[index] = 10. 00; Note: . length NOT. length() It is a variable not a method. 23

Code to Read Data into Array for (index = 0; index < sales. length; index++) sales[index] = console. next. Double(); 24

Code to Print Array for (index = 0; index < sales. length; index++) System. out. print(sales[index] + " "); 25

Code to Find Sum and Average of Array sum = 0; for (index = 0; index < sales. length; index++) sum = sum + sales[index]; if (sales. length != 0) average = sum / sales. length; else average = 0. 0; 26

Determining Largest Element in Array max. Index = 0; for (index = 1; index < sales. length; index++) if (sales[max. Index] < sales[index]) max. Index = index; largest. Sale = sales[max. Index]; 27

Determining Largest Element in Array 28
![Determining Largest Element in Array After for loop executes, max. Index=7 largest. Sale=sales[max. Index]= Determining Largest Element in Array After for loop executes, max. Index=7 largest. Sale=sales[max. Index]=](http://slidetodoc.com/presentation_image_h2/8641a476ffdb66a49cf4b22c91963709/image-29.jpg)
Determining Largest Element in Array After for loop executes, max. Index=7 largest. Sale=sales[max. Index]= 98. 23. Exercises: s How to find the smallest element in an array? ? s Rewrite the program that we discussed in the beginning of this chapter: the Rev. Ord class. 29

Array Index Out of Bounds s An array is in bounds if: 0 <= index <= array. Size – 1 s If index < 0 or index > array. Size: Array. Index. Out. Of. Bounds. Exception exception is thrown. If the program does not handle this exception, the program terminates. 30

Base address: s Base address: is the address (memory location) of the first component in an array. s Base address of list is the address of list[0]. s Value of variable list is the base address of the array= the address of list[0]. s When you pass an array as a parameter, the base address of the actual array is passed to the formal parameter. 31

Declaring Arrays as Formal Parameters to Methods General syntax to declare an array as a formal parameter: data. Type[] array. Name public static void arrays. As. Formal. Parameter(int[] list. A, double[] list. B, int num) { //. . . } int[] int. List = new int[10]; double[] double. Num. List = new double[15]; int number; arrays. As. Formal. Parameter(int. List, double. Num. List, number); 32

The Assignment Operators and Arrays int list. A={5, 10, 15, 20, 25, 30, 35}; int list. B=new int[list. A. length]; 33

The Assignment Operators and Arrays s You can use the assignment operator(=) to assign list. A to list. B. However, the result obtained might not be what you expect. s For example: list. A = list. B; s You expect: element of list. A are copied to list. B. s That is wrong, list. A is a refrence varible, both list. A and list. B refer to the same array. 34

The Assignment Operators and Arrays 35

The Assignment Operators and Arrays To copy list. A components to list. B: for (int index = 0; index < list. A. length; index++) list. B[index] = list. A[index]; 36

Relational Operators Arrays if (list. A == list. B). . . s The expression list. A == list. B determines if the values of list. A and list. B are the same, thus determining whether list. A and list. B refer to the same array. s To determine whether list. A and list. B contain the same elements, you need to compare them component by component. s You can write a method that returns true if two int arrays contain the same elements. 37
![Relational Operators and Arrays boolean is. Equal. Arrays(int[] first. Array, int[] second. Array) { Relational Operators and Arrays boolean is. Equal. Arrays(int[] first. Array, int[] second. Array) {](http://slidetodoc.com/presentation_image_h2/8641a476ffdb66a49cf4b22c91963709/image-38.jpg)
Relational Operators and Arrays boolean is. Equal. Arrays(int[] first. Array, int[] second. Array) { if (first. Array. length != second. Array. length) return false; for (int index = 0; index < first. Array. length; index++) if (first. Array[index] != second. Array[index]) return false; return true; } if (is. Equal. Arrays(list. A, list. B)). . . 38
![Methods for Array Processing Example 9_5 public static void fill. Array(int[] list, int no. Methods for Array Processing Example 9_5 public static void fill. Array(int[] list, int no.](http://slidetodoc.com/presentation_image_h2/8641a476ffdb66a49cf4b22c91963709/image-39.jpg)
Methods for Array Processing Example 9_5 public static void fill. Array(int[] list, int no. Of. Elements) { int index; for (index = 0; index < no. Of. Elements; index++) list[index] = console. next. Int(); } 39
![Methods for Array Processing public static void print. Array(int[] list, int no. Of. Elements) Methods for Array Processing public static void print. Array(int[] list, int no. Of. Elements)](http://slidetodoc.com/presentation_image_h2/8641a476ffdb66a49cf4b22c91963709/image-40.jpg)
Methods for Array Processing public static void print. Array(int[] list, int no. Of. Elements) { int index; for (index = 0; index < no. Of. Elements; index++) System. out. print(list[index] + " "); } public static int sum. Array(int[] list, int no. Of. Elements) { int index; int sum = 0; for (index = 0; index < no. Of. Elements; index++) sum = sum + list[index]; return sum; } 40
![Methods for Array Processing public static int index. Largest. Element(int[] list, int no. Of. Methods for Array Processing public static int index. Largest. Element(int[] list, int no. Of.](http://slidetodoc.com/presentation_image_h2/8641a476ffdb66a49cf4b22c91963709/image-41.jpg)
Methods for Array Processing public static int index. Largest. Element(int[] list, int no. Of. Elements) { int index; int max. Index = 0; for (index = 1; index < no. Of. Elements; index++) if (list[max. Index] < list[index]) max. Index = index; return max. Index; } public static void copy. Array(int[] list 1, int[] list 2, int no. Of. Elements) { int index; for (index = 0; index < no. Of. Elements; index++) list 2[index] = list 1[index]; } 41

Methods for Array Processing You MUST Check example 9_6 for calling these methods. 42

Parallel Arrays s Arrays are parallel if the corresponding components hold related information. s Example: You need to keep track of 50 students ID with their grades. Int [] student. Id = new int[50]; Char[] course. Grade = new char[50]; student. Id[3] and course. Grade[3] holds the data for the same student. Id 2345 4563 4590 2404 course. Grade A C C B 43

Arrays of Objects s Can use arrays to manipulate objects. s Example: Create an array named array 1 with N objects of type T: T[] array 1 = new T[N] s Can instantiate array 1 as follows: for(int j=0; j <array 1. length; j++) array 1[j] = new T(); 44
![Array of String Objects String[] name. List = new String[5]; name. List[0] name. List[1] Array of String Objects String[] name. List = new String[5]; name. List[0] name. List[1]](http://slidetodoc.com/presentation_image_h2/8641a476ffdb66a49cf4b22c91963709/image-45.jpg)
Array of String Objects String[] name. List = new String[5]; name. List[0] name. List[1] name. List[2] name. List[3] = = "Amanda Green"; "Vijay Arora"; "Sheila Mann"; "Rohit Sharma"; name. List[4] = "Mandy Johnson"; 45

Array of String Objects 46

Array of String Objects s You can use String methods to work with the objects of name. List. s name. List[0]. equals(“Amanda Green”) // true s name. List[4]. substring(0, 5) //Mandy 47
![Arrays of Objects of Other Classes Clock[] arrival. Time. Emp = new Clock[100]; 48 Arrays of Objects of Other Classes Clock[] arrival. Time. Emp = new Clock[100]; 48](http://slidetodoc.com/presentation_image_h2/8641a476ffdb66a49cf4b22c91963709/image-48.jpg)
Arrays of Objects of Other Classes Clock[] arrival. Time. Emp = new Clock[100]; 48

Instantiating Array Objects for (int j = 0; j < arrival. Time. Emp. length; j++) arrival. Time. Emp[j] = new Clock(); 49
![Instantiating Array Objects arrival. Time. Emp[49]. set. Time(8, 5, 10); 50 Instantiating Array Objects arrival. Time. Emp[49]. set. Time(8, 5, 10); 50](http://slidetodoc.com/presentation_image_h2/8641a476ffdb66a49cf4b22c91963709/image-50.jpg)
Instantiating Array Objects arrival. Time. Emp[49]. set. Time(8, 5, 10); 50

Arrays and Variable Length Parameter List s The syntax to declare a variable length formal parameter (list) is: data. Type. . . identifier 51

Arrays and Variable Length Parameter List public static double largest(double. . . num. List) { double max; int index; if (num. List. length != 0) { max = num. List[0]; for (index = 1; index < num. List. length; index++) { if (max < num. List [index]) max = num. List [index]; } return max; } return 0. 0; } 52
![Arrays and Variable Length Parameter List double[] number. List = {18. 50, 44, 56. Arrays and Variable Length Parameter List double[] number. List = {18. 50, 44, 56.](http://slidetodoc.com/presentation_image_h2/8641a476ffdb66a49cf4b22c91963709/image-53.jpg)
Arrays and Variable Length Parameter List double[] number. List = {18. 50, 44, 56. 23, 17. 89 92. 34, 112. 0, 77, 11, 22, 86. 62); System. out. println(largest(number. List)); 53

Arrays and Variable Length Parameter List Rules to follow when using a variable length formal parameter list: 1. A method can have both a variable length formal parameter and other formal parameter. public static void my. Method (String name, double num, int … int. List) 2. A method can have at most one varible length formal parameter. 3. If a method has both a variable length formal parameter and other formal parameter, then the variable length formal parameter must be the last). 54

foreach loop s The most recent version of Java provides a special type of for loop to process the elements of an objects such as an array. s The syntax to use this for loop to process the elements of an array is: for (data. Type identifier : array. Name) statements s identifier is a variable, and the data type of identifier is the same as the data type of the array components. s This form of for is called a foreach loop. 55

foreach loop sum = 0; for (double num : list) sum = sum + num; //line 1 //line 2 //line 3 s The for statement in Line 2 is read for each num in list. The identifier num is initialized to list[0]. In the next iteration, the value of num is list[1], and so on. for (double num : num. List) { if (max < num) max = num; } 56
![Two-Dimensional Arrays in. Stock [Red] [Brown] [Black] [White] [Gray] [GM] 10 4 95 3 Two-Dimensional Arrays in. Stock [Red] [Brown] [Black] [White] [Gray] [GM] 10 4 95 3](http://slidetodoc.com/presentation_image_h2/8641a476ffdb66a49cf4b22c91963709/image-57.jpg)
Two-Dimensional Arrays in. Stock [Red] [Brown] [Black] [White] [Gray] [GM] 10 4 95 3 5 [Ford] 6 3 6 6 4 [Toyota] 3 5 3 6 7 [BMW] 8 2 7 5 3 [Nissan] 0 4 5 33 4 [Volvo] 1 5 7 9 7 57

Two-Dimensional Arrays s Data is sometimes in table form (difficult to represent using a one-dimensional array). s To declare/instantiate a two-dimensional array: data. Type[ ][ ] array. Name = new data. Type[int. Exp 1][int. Exp 2]; s To access a component of a two-dimensional array: array. Name[index. Exp 1][index. Exp 2]; s int. Exp 1, int. Exp 2 >= 0 s index. Exp 1 = row position s index. Exp 2 = column position 58
![Two-Dimensional Arrays double[][]sales = new double[10][5]; 59 Two-Dimensional Arrays double[][]sales = new double[10][5]; 59](http://slidetodoc.com/presentation_image_h2/8641a476ffdb66a49cf4b22c91963709/image-59.jpg)
Two-Dimensional Arrays double[][]sales = new double[10][5]; 59

Accessing Two-Dimensional Array Components =25. 75 60
![Two-Dimensional Arrays int [][] matrix = new int[20][15]; 20 rows 15 columns matrix. length Two-Dimensional Arrays int [][] matrix = new int[20][15]; 20 rows 15 columns matrix. length](http://slidetodoc.com/presentation_image_h2/8641a476ffdb66a49cf4b22c91963709/image-61.jpg)
Two-Dimensional Arrays int [][] matrix = new int[20][15]; 20 rows 15 columns matrix. length = 20 //number of rows s Each row of matrix is 1 -D array matrix. [0]. length = 15 //# of columns in 1 st row matrix. [1]. length = 15 // # of columns in 2 nd row 61

Two-Dimensional Arrays: Special Cases s Can specify different number of columns for each row (ragged arrays). In this case, each row must be instantiated separately. 62

Two-Dimensional Arrays: Special Cases To create this array, first we create 1 -D array board of 5 rows: int[] board = new int[5]; board[0] board[1] board[2] board[3] board[4] = = = new new new int[6]; int[2]; int[3]; int[4]; 63
![Two Dimensional Array Initialization During Declaration int[][] board = {{2, 3, 1} , {15, Two Dimensional Array Initialization During Declaration int[][] board = {{2, 3, 1} , {15,](http://slidetodoc.com/presentation_image_h2/8641a476ffdb66a49cf4b22c91963709/image-64.jpg)
Two Dimensional Array Initialization During Declaration int[][] board = {{2, 3, 1} , {15, 25, 13} , {20, 4, 7}}; board [0] [1] [2] [0] 2 3 1 [1] 15 25 13 [2] 20 4 7 What is the array created after this statement: int[][] table = {{2, 3, 1, 5} , {15, 25} , {4, 23, 45}}; 64

Processing Two Dimensional Array s Three ways to process two-dimensional arrays: s Entire array. s Particular row of array (row processing). s Particular column of array (column processing). s Processing algorithms is similar to processing algorithms of one-dimensional arrays. s The following declarations are used for our examples: static final int ROWS=7; static final int COLUMNS=6; int[][] matrix = new int [ROWS][COLUMNS]; int row, col, sum, largest, temp; 65

Two-Dimensional Arrays: Processing s Loop for processing row 5 elements: for (col=0; col < matrix[5]. length; col++) //process matrix[5][col] s Loop for processing column 2 elements: for (row=0; row < matrix. length; row++) //process matrix[row][2] 66

Two-Dimensional Arrays: Processing Initialization for (row = 0; row < matrix. length; row++) for (col = 0; col < matrix[row]. length; col++) matrix[row][col] = 10; Print for (row = 0; row < matrix. length; row++) { for (col = 0; col < matrix[row]. length; col++) System. out. printf("%7 d", matrix[row][col]); System. out. println(); } 67

Two-Dimensional Arrays: Processing Input for (row = 0; row < matrix. length; row++) for (col = 0; col < matrix[row]. length; col++) matrix[row][col] = console. next. Int(); Sum by Row for (row = 0; row < matrix. length; row++) { sum = 0; for (col = 0; col < matrix[row]. length; col++) sum = sum + matrix[row][col]; System. out. println("Sum of row " + (row + 1) + " = "+ sum); } 68
![Two-Dimensional Arrays: Processing Sum by Column for (col = 0; col < matrix[0]. length; Two-Dimensional Arrays: Processing Sum by Column for (col = 0; col < matrix[0]. length;](http://slidetodoc.com/presentation_image_h2/8641a476ffdb66a49cf4b22c91963709/image-69.jpg)
Two-Dimensional Arrays: Processing Sum by Column for (col = 0; col < matrix[0]. length; col++) { sum = 0; for (row = 0; row < matrix. length; row++) sum = sum + matrix[row][col]; System. out. println("Sum of column " + (col + 1) + " = " + sum); } 69

Two-Dimensional Arrays: Processing Largest Element in Each Row for (row = 0; row < matrix. length; row++) { largest = matrix[row][0]; for (col = 1; col < matrix[row]. length; col++) if (largest < matrix[row][col]) largest = matrix[row][col]; System. out. println("The largest element of row " + (row + 1) + " = " + largest); } 70

Two-Dimensional Arrays: Processing Largest Element in Each Column for (col = 0; col < matrix[0]. length; col++) { largest = matrix[0][col]; for (row = 1; row < matrix. length; row++) if (largest < matrix[row][col]) largest = matrix[row][col]; System. out. println("The largest element of col " + (col + 1) + " = " + largest); } 71

Multidimensional Arrays s Can define three-dimensional arrays or n-dimensional arrays (n can be any number). s Syntax to declare and instantiate array: data. Type[][]…[] array. Name = new data. Type[int. Exp 1][int. Exp 2]…[int. Expn]; s Syntax to access component: array. Name[index. Exp 1][index. Exp 2]…[index. Expn] s int. Exp 1, int. Exp 2, . . . , int. Expn = positive integers s index. Exp 1, index. Exp 2, . . . , index. Expn = non-negative integers 72
![Loops to Process Multidimensional Arrays double[][][] car. Dealers = new double[10][5][7]; for (i = Loops to Process Multidimensional Arrays double[][][] car. Dealers = new double[10][5][7]; for (i =](http://slidetodoc.com/presentation_image_h2/8641a476ffdb66a49cf4b22c91963709/image-73.jpg)
Loops to Process Multidimensional Arrays double[][][] car. Dealers = new double[10][5][7]; for (i = 0; i < 10; i++) for (j = 0; j < 5; j++) for (k = 0; k < 7; k++) car. Dealers[i][j][k] = 10. 00; 73

Chapter 10: Applications of Arrays Java Programming: From Problem Analysis to Program Design, Second Edition

Chapter Objectives s Learn how to implement the sequential search algorithm. s Explore how to sort an array using selection sort. s Become aware of the class Vector. s Become aware of the Wrapper classes. Java Programming: From Problem Analysis to Program Design, Second Edition 75

List Processing s List: A set of values of the same type. s Basic operations performed on a list: s s Search list for given item. Sort list. Insert item in list. Delete item from list. Java Programming: From Problem Analysis to Program Design, Second Edition 76

Search s Necessary components to search a list: s Array containing the list. s Length of the list. s Item for which you are searching. s After search completed: s If item found, report “success” and return location in array. s If item not found, report “failure. ” Java Programming: From Problem Analysis to Program Design, Second Edition 77
![Search public static int seq. Search(int[] list, int list. Length, int search. Item) { Search public static int seq. Search(int[] list, int list. Length, int search. Item) {](http://slidetodoc.com/presentation_image_h2/8641a476ffdb66a49cf4b22c91963709/image-78.jpg)
Search public static int seq. Search(int[] list, int list. Length, int search. Item) { int loc; boolean found = false; for (loc = 0; loc < list. Length; loc++) if (list[loc] == search. Item) { found = true; break; } if (found) return loc; else return -1; } Java Programming: From Problem Analysis to Program Design, Second Edition 78

Selection Sort s List is sorted by selecting list element and moving it to its proper position. s Algorithm finds position of smallest element and moves it to top of unsorted portion of list. s Repeats process above until entire list is sorted. Java Programming: From Problem Analysis to Program Design, Second Edition 79

Selection Sort Java Programming: From Problem Analysis to Program Design, Second Edition 80

Selection Sort Java Programming: From Problem Analysis to Program Design, Second Edition 81
![Selection Sort public static void selection. Sort(int[] list, int list. Length) { int index; Selection Sort public static void selection. Sort(int[] list, int list. Length) { int index;](http://slidetodoc.com/presentation_image_h2/8641a476ffdb66a49cf4b22c91963709/image-82.jpg)
Selection Sort public static void selection. Sort(int[] list, int list. Length) { int index; int smallest. Index; int min. Index; int temp; for (index = 0; index < list. Length – 1; index++) { smallest. Index = index; for (min. Index = index + 1; min. Index < list. Length; min. Index++) if (list[min. Index] < list[smallest. Index]) smallest. Index = min. Index; temp = list[smallest. Index]; list[smallest. Index] = list[index]; list[index] = temp; } } Java Programming: From Problem Analysis to Program Design, Second Edition 82

Selection Sort s For a list of length n, an average selection sort makes n(n – 1) / 2 key comparisons and 3(n – 1) item assignments. s Therefore, if n = 1000, selection sort makes about 500, 000 key comparisons and about 3000 item assignments to sort the list. Java Programming: From Problem Analysis to Program Design, Second Edition 83

Vectors s The class Vector can be used to implement a list. s Unlike an array, the size of a Vector object can grow/shrink during program execution. s You do not need to worry about the number of data elements in a vector. Java Programming: From Problem Analysis to Program Design, Second Edition 84

Members of the class Vector Java Programming: From Problem Analysis to Program Design, Second Edition 85

Members of the class Vector Java Programming: From Problem Analysis to Program Design, Second Edition 86

Members of the class Vector Java Programming: From Problem Analysis to Program Design, Second Edition 87

Members of the class Vector Java Programming: From Problem Analysis to Program Design, Second Edition 88

Vectors s Every element of a Vector object is a reference variable of the type Object. s To add an element into a Vector object: s Create appropriate object. s Store data into object. s Store address of object holding data into Vector object element. Java Programming: From Problem Analysis to Program Design, Second Edition 89

Vectors Vector<String> string. List = new Vector<String>(); string. List. add. Element("Spring"); string. List. add. Element("Summer"); string. List. add. Element("Fall"); string. List. add. Element("Winter"); Java Programming: From Problem Analysis to Program Design, Second Edition 90

Wrapper Classes s Algorithms are used to implement operations. s Construct and implement your own methods. s Classes Integer, Double, Character, Long, Float: s Known as wrapper classes. s Provided so that values of primitive data types can be treated as objects. s Have limitations (cannot change value stored in objects). Java Programming: From Problem Analysis to Program Design, Second Edition 91

The class Integer Java Programming: From Problem Analysis to Program Design, Second Edition 92

The class Integer Java Programming: From Problem Analysis to Program Design, Second Edition 93

The class Integer num; num = new Integer(86) Java Programming: From Problem Analysis to Program Design, Second Edition 94

The class Integer int x; Integer num; num = 25; This statement is equivalent to the statement: num = new Integer(25); The expression: num = 25; is referred to as autoboxing of the int type. Java Programming: From Problem Analysis to Program Design, Second Edition 95

The class Integer int x; Integer num; The statement: x = num; This statement is equivalent to the statement: x = num. int. Value(); This statement is referred to as auto unboxing of the int type. Java Programming: From Problem Analysis to Program Design, Second Edition 96

The class Integer s To compare the values of two Integer objects, you can use the method compare. To. s If you want to compare the values of two Integer objects only for equality, then you can use the method equal. Java Programming: From Problem Analysis to Program Design, Second Edition 97

The class Int. Class Java Programming: From Problem Analysis to Program Design, Second Edition 98

The class Int. Class Java Programming: From Problem Analysis to Program Design, Second Edition 99
- Slides: 99