OBJECT ORIENTED PROGRAMMING II LECTURE 15 GEORGE KOUTSOGIANNAKIS

Slides:



Advertisements
Similar presentations
Arrays.
Advertisements

Arrays.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
C++ for Engineers and Scientists Third Edition
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Chapter 8 Single-Dimensional Arrays. Topics Declaring and Instantiating Arrays Accessing Array Elements Writing Methods Aggregate Array Operations Using.
04/29/ Introduction to Vectors?... A vector is a dynamic array. - It can be expanded and shrunk as required - A Component of a vector can be accessed.
ArrayList, Multidimensional Arrays
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Java Programming: From Problem Analysis to Program Design, 4e
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Chapter 9 Multidimensional Arrays and the ArrayList Class.
Java SE 8 for Programmers, Third Edition
CSC 211 Data Structures Lecture 13
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Chapter 4: Control Structures II
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
Chapter overview This chapter focuses on Array declaration and use Bounds checking and capacity Arrays storing object references Variable length parameter.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
How do you do the following? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include.
Application development with Java Lecture 6 Rina Zviel-Girshin.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 5 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis 1.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
CS 116: Object Oriented Programming II. Topics Vectors Multidimensional Arrays ArrayList.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 4 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis 1.
CS 116 Object Oriented Programming II Lecture 4 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis 1.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
Chapter 9 Introduction to Arrays Fundamentals of Java.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Chapter 5 Arrays F Introducing Arrays F Declaring Array Variables, Creating Arrays, and Initializing Arrays F Passing Arrays to Methods F Copying Arrays.
Arrays Chapter 7.
Chapter 16: Searching, Sorting, and the vector Type
Chapter 11 - JavaScript: Arrays
Arrays Chapter 7.
EGR 2261 Unit 10 Two-dimensional Arrays
OBJECT ORIENTED PROGRAMMING II LECTURE 23 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING I LECTURE 12 GEORGE KOUTSOGIANNAKIS
Computer Programming BCT 1113
Recitation 13 Searching and Sorting.
JavaScript: Functions.
Arrays … The Sequel Applications and Extensions
Java How to Program, Late Objects Version, 10/e
Can store many of the same kind of data together
Chapter 5 Arrays Introducing Arrays
Introduction To Programming Information Technology , 1’st Semester
Can store many of the same kind of data together
Object Oriented Programming in java
24 Searching and Sorting.
Data Structures (CS212D) Week # 2: Arrays.
Arrays Chapter 7.
OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS
Arrays Week 2.
OBJECT ORIENTED PROGRAMMING II LECTURE 13_2 GEORGE KOUTSOGIANNAKIS
Can store many of the same kind of data together
OBJECT ORIENTED PROGRAMMING II LECTURE 4 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
10 JavaScript: Arrays.
C++ Array 1.
Arrays.
Presentation transcript:

OBJECT ORIENTED PROGRAMMING II LECTURE 15 GEORGE KOUTSOGIANNAKIS CS 201 OBJECT ORIENTED PROGRAMMING II LECTURE 15 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis

Last week’s topics Finding the Max and Min element value. Copying Arrays /Changing the size of an array. Searching Arrays. Selection Sort .

This week’ s topics Binary Search of an array. Using Arrays as counters. Vectors. Multi-dimensional Arrays

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.

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.

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.

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.  

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.

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.

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.

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.

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.

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

Example Code See Examples 8.22 Die.java, 8.23 DieCount.java // 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

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.

Vectors Vector v=new Vector(); Auto car1=new Auto(); 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).

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.

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

Constructor Summary Vector()           Constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero. Vector(Collection<? extends E> c)           Constructs a vector containing the elements of the specified collection, in the order they are returned by the collection's iterator. Vector(int initialCapacity)           Constructs an empty vector with the specified initial capacity and with its capacity increment equal to zero. Vector(int initialCapacity, int capacityIncrement)           Constructs an empty vector with the specified initial capacity and capacity increment.

Some of the available Methods (see API for complete listing)  boolean add(E e)           Appends the specified element to the end of this Vector.  void add(int index, E element)           Inserts the specified element at the specified position in this Vector. void clear()           Removes all of the elements from this Vector. E (where E is the specific Object type stored) elementAt(int index)           Returns the component at the specified index. addElement(E obj)           Adds the specified component to the end of this vector, increasing its size by one   set(int index, E element)           Replaces the element at the specified position in this Vector with the specified element.

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.

Declaring Multidimensional Arrays Declaring a two-dimensional array: datatype [][] arrayName; or datatype [][] arrayName1, arrayName2, …; Declaring a three-dimensional array: datatype [][][] arrayName; datatype [][][] arrayName1, arrayName2, …; Examples: double [][] dailyTemps, weeklyTemps; Auto [][][] cars;

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.

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.

Assigning Initial Values Example For example, this statement: int [][] numbersList1 = { { 0, 5, 10 }, { 0, 3, 6, 9 } };

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.

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

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

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

Accessing Two-Dimensional Array Elements Syntax 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

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

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

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

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.

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.

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.

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:  1st dimension: year 2nd dimension: week 3rd dimension: day of the week

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;

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

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

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:  1st dimension: state 2nd dimension: year 3rd dimension: week 4th dimension: day of the week

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

Study Guide Chapter 8 Vectors not covered by text (see presentation). 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.