Download presentation
Presentation is loading. Please wait.
Published byDoris Collins Modified over 9 years ago
1
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 5 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis 1
2
Last week’s topics Finding the Max and Min element value. Copying Arrays /Changing the size of an array. Searching Arrays. Selection Sort. 2
3
This week’ s topics Binary Search of an array. Using Arrays as counters. Vectors. Multi-dimensional Arrays 3
4
Binary Search A Binary Search is like the "Guess a Number" game. To guess a number between 1 and 100, we start with 50 (halfway between the beginning number and the end number). – If we learn that the number is greater than 50, we immediately know the number is not 1 - 49. – If we learn that the number is less than 50, we immediately know the number is not 51 - 100. We keep guessing the number that is in the middle of the remaining numbers (eliminating half the remaining numbers) until we find the number. 4
5
Binary Search The "Guess a Number" approach works because 1 - 100 are a "sorted" set of numbers. To use a Binary Search, the array must be sorted. Our Binary Search will attempt to find a search key in a sorted array. – If the search key is found, we return the index of the element with that value. – If the search key is not found,we return -1. 5
6
The Binary Search Algorithm We begin by comparing the middle element of the array and the search key. – If they are equal, we found the search key and return the index of the middle element. – If the middle element's value is greater than the search key, then the search key cannot be found in elements with higher array indexes. So, we continue our search in the left half of the array. – If the middle element's value is less than the search key, then the search key cannot be found in elements with lower array indexes. So, we continue our search in the right half of the array. 6
7
The Binary Search Algorithm (cont’d) As we keep searching, the subarray we search keeps shrinking in size. In fact, the size of the subarray we search is cut in half at every iteration. If the search key is not in the array, the subarray we search will eventually become empty. At that point, we know that we will not find our search key in the array, and we return –1. 7
8
Example of a Binary Search We will search for the value 7 in this sorted array: To begin, we find the index of the center element, which is 8, and we compare our search key (7) with the value 45. 8
9
Binary Search Example (cont’d) Because 7 is less than 45, we eliminate all array elements higher than our current middle element and consider elements 0 through 7 the new subarray to search. The index of the center element is now 3, so we compare 7 to the value 8. 9
10
Binary Search Example (cont’d) Because 7 is less than 8, we eliminate all array elements higher than our current middle element (3) and make elements 0 through 2 the new subarray to search. The index of the center element is now 1, so we compare 7 to the value 6. 10
11
Binary Search: Finding the Search Key Because 7 is greater than 6, we eliminate array elements lower than our current middle element (1) and make element 2 the new subarray to search. The value of element 2 matches the search key, so our search is successful and we return the index 2. 11
12
Binary Search Code public int binarySearch( int [] array, int key ) { int start = 0, end = array.length - 1; while ( end >= start ) { int middle = ( start + end ) / 2; if ( array[middle] == key ) return middle; // key found else if ( array[middle] > key ) end = middle - 1; // search left else start = middle + 1; // search right } return -1; // key not found } Note: Assumes that the items are sorted from smaller to largest. 12
13
Using Arrays as Counters To count multiple items, we can use an array of integers. – Each array element is a counter Example: we want to throw a die and count the number of times each side is rolled – We set up an array of 6 integer counters, initialized to 0 – For each roll, we use ( roll - 1 ) as the index of the array element to increment 13
14
Example Code // instantiate array of counters int [] rollCount = new int [6]; // roll the die NUMBER_OF_ROLLS times for ( int i = 1; i <= NUMBER_OF_ROLLS; i++ ) { // roll the die int roll = (int) Math.random( ) * 6 + 1; // increment the corresponding counter rollCount[roll - 1]++; } See Examples 8.22 Die.java, 8.23 DieCount.java 14
15
Vectors Using vectors could be better than using arrays in some cases: – Vectors can adjust their size dynamically. Ideal for cases where we don’t know the size of thedata involved. Vector class is part of the java.util package. Vectors accept only Object data types. You can not insert primitive data types. – When reading the object from the vector you have to type casted back to the Class that the object belongs to. Vectors are easier to sort, search,remove elements, or add elements than arrays. – The same vector object can object multiple object types (i.e. Auto, Student, Person objects). This is something that arrays can not do. 15
16
Vectors Vector v=new Vector(); – Constructs a vector of default size 10. Size will be incremented as needed. Notice that the class has other constructors also. Auto car1=new Auto(); v.addElement(car1) ; adds the object car1 to the end of the vector and increases its size by 1. Object mycarobj=v.elementAt(i); Auto mycar=(Auto)mycarobj; returns the object stored at index i. Notice that it is a two step process: – First we retrieve the object as a generalized Object type. – Then we type casted to the specific object type (we have to know what the object type is). 16
17
Vectors v.remove(i); removes the element at index i. adjusts the size of the vector. v.set(int i, Object obj); replaces the object stored originally at index i with the new object obj. v.add(int i, Object obj) sets the object obj at index i. Pushes the existing object at index I,and everything else after it, one position down in the vector. It increases the size of the vector by 1. 17
18
Vectors-Example import java.util.*; public class UseVectors {public static void main(String[] args) { Vector v=new Vector(); VehicleA car1=new VehicleA(); VehicleA car2=new VehicleA(); v.addElement(car1); v.addElement(car2); Object o1=v.elementAt(0); VehicleA veh1=(VehicleA)o1; veh1.setDistance(5.0); System.out.println(veh1.toString()); //place it back in the same index after updating its attribute distance v.set(o, veh1); } 18
19
19 Constructor Summary VectorVector() Constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero. VectorVector(Collection c) Constructs a vector containing the elements of the specified collection, in the order they are returned by the collection's iterator.CollectionE VectorVector(int initialCapacity) Constructs an empty vector with the specified initial capacity and with its capacity increment equal to zero. VectorVector(int initialCapacity, int capacityIncrement) Constructs an empty vector with the specified initial capacity and capacity increment.
20
20 Some of the available Methods (see API for complete listing) boolean addadd(E e) Appends the specified element to the end of this Vector.E void addadd(int index, E element) Inserts the specified element at the specified position in this Vector.E void clearclear() Removes all of the elements from this Vector. EE (where E is the specific Object type stored) elementAtelementAt(int index) Returns the component at the specified index. void addElementaddElement(E obj) Adds the specified component to the end of this vector, increasing its size by oneE E (where E is the specific Object type stored) setset(int index, E element) Replaces the element at the specified position in this Vector with the specified element.E
21
Multidimensional Arrays Two-Dimensional Arrays Allows organization of data in rows and columns in a table-like representation Example: Daily temperatures can be arranged as 52 weeks with 7 days each. 21
22
Declaring Multidimensional Arrays Declaring a two-dimensional array: datatype [][] arrayName; or datatype [][] arrayName1, arrayName2, …; Declaring a three-dimensional array: datatype [][][] arrayName; or datatype [][][] arrayName1, arrayName2, …; Examples: double [][] dailyTemps, weeklyTemps; Auto [][][] cars; 22
23
Instantiating Multidimensional Arrays Instantiating a two-dimensional array: arrayName = new datatype [exp1][exp2]; where exp1 and exp2 are expressions that evaluate to integers and specify, respectively, the number of rows and the number of columns in the array. Example: dailyTemps = new double [52][7]; dailyTemps has 52 rows and 7 columns, for a total of 364 elements. 23
24
Assigning Initial Values datatype [][] arrayName = { { value00, value01, … }, { value10, value11, …}, … }; where valueMN is an expression that evaluates to the data type of the array and is the value to assign to the element at row M and column N. – The number of sublists is the number of rows in the array. – The number of values in each sublist determines the number of columns in that row. Thus, a two-dimensional array can have a different number of columns in each row. Note that each {…… } separated by coma represents one row’s data. 24
25
Assigning Initial Values Example For example, this statement: int [][] numbersList1 = { { 0, 5, 10 }, { 0, 3, 6, 9 } }; 25
26
An Array of Arrays As the preceding figure illustrates, a two- dimensional array is an array of arrays. – The first dimension of a two-dimensional array is an array of array references, with each reference pointing to a single-dimensional array. – Thus, a two-dimensional array is comprised of an array of rows, where each row is a single- dimensional array. 26
27
Instantiating Arrays with Different Length Rows To instantiate a two-dimensional array whose rows have a different number of columns: 1. instantiate the two-dimensional array 2. instantiate each row as a single-dimensional array //instantiate the array with 3 rows char [][] grades = new char [3][]; // instantiate each row grades[0] = new char [23]; // instantiate row 0 grades[1] = new char [16]; // instantiate row 1 grades[2] = new char [12]; // instantiate row 2 27
28
Accessing Array Elements Elements of a two-dimensional array are accessed using this syntax: arrayName[exp1][exp2] – exp1 is the element's row index row index of first row: 0 row index of last row: number of rows - 1 – exp2 is the element's column index column index of first column: 0 column index of last column: number of columns in that row - 1 28
29
The Length of the Array The number of rows in a two-dimensional array is: arrayName.length The number of columns in row n in a two- dimensional array is: arrayName[n].length 29
30
Accessing Two-Dimensional Array Elements Array elementSyntax Row 0, column j arrayName[0][j] Row i, column j arrayName[i][j] Last row, column j arrayName[arrayName.length – 1][j] Last row, last column arrayName[arrayName.length – 1] [arrayName [arrayName.length -1].length – 1] Number of rows arrayName.length Number of columns in row i arrayName[i].length 30
31
Output all the elements of a two- dimensional array To process all array elements in row order, we use a nested for loop: for ( int i = 0; i < arrayName.length; i++ ) { for ( int j = 0; j < arrayName[i].length; j++ ) { // process element arrayName[i][j] } – The outer loop processes the rows. – The inner loop processes the columns within each row. See Example 9.3 OutputFamilyCellBills.java 31
32
Processing a Given Row Suppose we had an array where the rows represent months of the year and columns represent the various categories of expenditures (i.e. CarExpenses, FoodExpenses, RestaurantExpenses etc.) If we want a listing of the expenses for a particular month then we need to process one row only (the row that represents the month). To process just row i, we use this standard form: for ( int j = 0; j < arrayName[i].length; j++ ) { // process element arrayName[i][j] } Notice that we iterate through the elements of the row column by column where a column is identified by j. Also notice that arrayName[i].length returns the size of the array that represents that particular row (ith row). 32
33
Processing a Given Column If we want to list all the expenditures for the whole year for a particular type of an expenditure (i.e. FoodExpenses) then we need to process just one column. To process just column j, we use this standard form: for ( int i = 0; i < arrayName.length; i++ ) { if ( j < arrayName[i].length ) // process element arrayName[i][j] } Note: Because rows have variable lengths, we must verify that the current row has a column j before attempting to process the element. Also notice that arrayName.length returns the number of rows of the array 33
34
Arrays where not all columns have the same size Suppose we want to store test grades for three courses. Each course has a different number of tests, so each row has a different number of columns: int [][] grades = { { 89, 75 }, { 84, 76, 92, 96 }, { 80, 88, 95 } }; First, we need to find the number of columns in the largest row. We use that in our loop condition. Then, before attempting to process the array element, we check whether the given column exists in the current row. 34
35
Arrays where not all rows have the same number of columns Suppose that we have stored the maximum number of columns in maxNumberOfColumns; the general pattern for processing elements one column at a time is: for ( int j = 0; j < maxNumberOfColumns; j++ ) { for ( int i = 0; i < arrayName.length; i++ ) { // does column j exist in this row? if ( j < arrayName[i].length ) { // process element arrayName[i][j] } Notice that this is different than slide 4. Here we scan through the columns and for each column (if it exists) we output the values in its rows. 35
36
Arrays where not all rows have the same number of columns Therefore first we scan column 0 to get values 0, 0 Next column 1 to get 5, 3 Next column 2 to get 10,6 Next column 4 but this column does not hav e row 0 therefore only row 1 has the value 9. In other words array[0].length returns 3 and when j=4 if(j<aarray[i].length) returns false. 36
37
Other Multidimensional Arrays If we want to keep track of sales on a per-year, per-week, and per-day basis, we could use a three-dimensional array: – 1 st dimension: year – 2 nd dimension: week – 3 rd dimension: day of the week 37
38
Sample Code // declare a three-dimensional array double [][][] sales; // instantiate the array for 10 years, 52 weeks, // and 7 days sales = new double [10][52][7]; // set the value of the first element sales[0][0][0] = 638.50; // set the value for year 4, week 22, day 3 sales [4][22][3] = 928.20; // set the last value in the array sales [9][51][6] = 1234.90; 38
39
Code to Print the sales Array for ( int i = 0; i < sales.length; i++ ) { for ( int j = 0; j < sales[i].length; j++ ) { for ( int k = 0; k < sales[i][j].length; k++ ) { // print the element at sales[i][j][k] System.out.print( sales[i][j][k] + "\t" ); } // skip a line after each week System.out.println( ); } // skip a line after each month System.out.println( ); } 39
40
General Pattern for Processing a Three-Dimensional Array for ( int i = 0; i < arrayName.length; i++ ) { for ( int j = 0; j < arrayName[i].length; j++ ) { for ( int k = 0; k <arrayName[i][j].length; k++ ) { // process the element arrayName[i][j][k] } 40
41
A Four-Dimensional Array If we want to keep track of sales on a per-state, per-year, per-week, and per-day basis, we could use a four-dimensional array: – 1 st dimension: state – 2 nd dimension: year – 3 rd dimension: week – 4 th dimension: day of the week 41
42
General Pattern for Processing a Four-Dimensional Array for ( int i = 0; i < arrayName.length; i++ ) { for ( int j = 0; j < arrayName[i].length; j++ ) { for ( int k = 0; k < arrayName[i][j].length; k++ ) { for ( int l = 0; l < arrayName[i][j][k].length; l++ ) { // process element arrayName[i][j][k][l] } 42
43
Study Guide Chapter 8 – Sections 8.6.6 and 8.8 Vectors not covered by text (see presentation). Chapter 9 – Section 9.1, 9.2, 9.3, 9.4, 9.6. 43
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.