CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 5 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis 1.

Slides:



Advertisements
Similar presentations
Arrays.
Advertisements

CHAPTER 10 ARRAYS II Applications and Extensions.
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.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
©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.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
C++ for Engineers and Scientists Third Edition
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Chapter 10 2D Arrays Collection Classes. Topics Arrays with more than one dimension Java Collections API ArrayList Map.
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.
Chapter 16: Searching, Sorting, and the vector Type.
A First Book of ANSI C Fourth Edition
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
ARRAYS 1 Week 2. Data Structures  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently 
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
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.
Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.
Java SE 8 for Programmers, Third Edition
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
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.
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.
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Arrays Chapter 7. 2 Declaring and Creating Arrays Recall that an array is a collection of elements all of the _____________ Array objects in Java must.
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 115 OBJECT ORIENTED PROGRAMMING I LECTURE 12 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
CS 116: Object Oriented Programming II. Topics Vectors Multidimensional Arrays ArrayList.
Arrays (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
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.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Chapter 9 Introduction to Arrays Fundamentals of Java.
Chapter 16: Searching, Sorting, and the vector Type.
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
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.
OBJECT ORIENTED PROGRAMMING II LECTURE 23 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 15 GEORGE KOUTSOGIANNAKIS
Java How to Program, Late Objects Version, 10/e
Can store many of the same kind of data together
Can store many of the same kind of data together
Object Oriented Programming in java
Arrays Chapter 7.
OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS
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
Arrays.
Presentation transcript:

CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 5 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis 1

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

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

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 – If we learn that the number is less than 50, we immediately know the number is not 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

Binary Search The "Guess a Number" approach works because 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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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] = ; // set the value for year 4, week 22, day 3 sales [4][22][3] = ; // set the last value in the array sales [9][51][6] = ; 38

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

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

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

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

Study Guide Chapter 8 – Sections and 8.8 Vectors not covered by text (see presentation). Chapter 9 – Section 9.1, 9.2, 9.3, 9.4,