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

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Lesson 8 Searching and Sorting Arrays 1CS 1 Lesson 8 -- John Cole.
Bubble Sort Algorithm 1.Initialize the size of the list to be sorted to be the actual size of the list. 2.Loop through the list until no element needs.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Chapter 9: Searching, Sorting, and Algorithm Analysis
Visual C++ Programming: Concepts and Projects
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 17: Linked Lists.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
Chapter 8 Search and Sort Asserting Java ©Rick Mercer.
C++ Plus Data Structures
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Sorting Algorithms: Selection, Insertion and Bubble.
CS 106 Introduction to Computer Science I 03 / 03 / 2008 Instructor: Michael Eckmann.
Algorithm Efficiency and Sorting
Unit 271 Searching and Sorting Linear Search Binary Search Selection Sort Insertion Sort Bubble (or Exchange) Sort Exercises.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
Arrays in Java Selim Aksoy Bilkent University Department of Computer Engineering
Programming Logic and Design Fourth Edition, Comprehensive
Searching and Sorting Arrays
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 9 Searching.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 03 / 17 / 2008 Instructor: Michael Eckmann.
Sorting and Searching Arrays CSC 1401: Introduction to Programming with Java Week 12 – Lectures 1 & 2 Wanda M. Kunkle.
Data Structures Using C++ 2E
- SEARCHING - SORTING.  Given:  The array  The search target: the array element value we are looking for  Algorithm:  Start with the initial array.
CSE 1301 J Lecture 13 Sorting Richard Gesick. CSE 1301 J 2 of 30 Sorting an Array When an array's elements are in random order, our Sequential Search.
Describing algorithms in pseudo code To describe algorithms we need a language which is: – less formal than programming languages (implementation details.
Chapter 8 ARRAYS Continued
One Dimensional Array. Introduction to Arrays Primitive variables are designed to hold only one value at a time. Arrays allow us to create a collection.
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Chapter 8 Single-Dimensional Arrays. Topics Declaring and Instantiating Arrays Accessing Array Elements Writing Methods Aggregate Array Operations Using.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 3 GEORGE KOUTSOGIANNAKIS Copyright: Illinois Institute of Technology/George Koutsogiannakis 1.
Chapter 8 Arrays and Strings
Data Structures & Algorithms CHAPTER 4 Searching Ms. Manal Al-Asmari.
Array Processing - 2. Objectives Demonstrate a swap. Demonstrate a linear search of an unsorted array Demonstrate how to search an array for a high value.
+ ARRAYS - SEARCHING - SORTING Dr. Soha S. Zaghloul updated by Rasha M. AL_Eidan 2015.
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.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 8 Search and Sort ©Rick Mercer. Outline Understand how binary search finds elements more quickly than sequential search Sort array elements Implement.
Searching & Sorting Programming 2. Searching Searching is the process of determining if a target item is present in a list of items, and locating it A.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 12 GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology/ George Koutsogiannakis 1.
1 Chapter 13-2 Applied Arrays: Lists and Strings Dale/Weems.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 14 Searching and Sorting.
CS 116: OBJECT ORIENTED PROGRAMMING II LECTURE 2 *Includes materials provided by George Koutsogiannakis and Matt Bauer 1.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
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 115 OBJECT ORIENTED PROGRAMMING I LECTURE 12 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
Data Structures Arrays and Lists Part 2 More List Operations.
Sorting & Searching Geletaw S (MSC, MCITP). Objectives At the end of this session the students should be able to: – Design and implement the following.
CS 116: OBJECT ORIENTED PROGRAMMING II LECTURE 3 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer 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.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 8: Searching and Sorting Arrays.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Chapter 5 Arrays F Introducing Arrays F Declaring Array Variables, Creating Arrays, and Initializing Arrays F Passing Arrays to Methods F Copying Arrays.
OBJECT ORIENTED PROGRAMMING I LECTURE 7 GEORGE KOUTSOGIANNAKIS
Introduction to Search Algorithms
OBJECT ORIENTED PROGRAMMING II LECTURE 2 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 2_1 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING I LECTURE 7 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 13_2 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 4 GEORGE KOUTSOGIANNAKIS
Arrays.
Presentation transcript:

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

OOP Review In previous lecture we discussed: – Declaring and Instantiating Arrays – Entering Array Elements – Accessing Array Elements – Aggregate Array Operations – Arrays of Objects. – Creating Packages 2

Arrays – Single Dimension Topics Copying Array Values. Enumerations. Searching Arrays. Selection Sort. 3

Copying Array Values Example This code copies the values of all elements in an array named cellBills to an array named billsBackup, both of which have previously been instantiated with the same length: for ( int i = 0; i < cellBills.length; i++ ) { billsBackup[i] = cellBills[i]; } The effect of this for loop is shown on the next slide. See Example 8.7 CopyingArrayElements.java 4

Copying Array Values (cont’d) A separate copy of the array has been created. 5

Changing an Array's Size An array's length instance variable is constant – that is, arrays are assigned a constant size when they are instantiated To expand an array while maintaining its original values: 1.Instantiate an array with the new size and a temporary name 2.Copy the original elements to the new array 3.Point the original array reference to the new array 4.Assign a null value to the temporary array reference 6

Comparing Arrays for Equality To compare whether the elements of two arrays are equal: 1.Determine if both arrays have the same length 2.Compare each element in the first array with the corresponding element in the second array To do this, we'll use a flag variable and a for loop. 7

Comparing cellBills1 to cellBills2 boolean isEqual = true; // flag variable if ( cellBills1.length != cellBills2.length ) isEqual = false; // sizes are different else { for ( int i = 0; i < cellBills1.length && isEqual; i++ ) { if ( Math.abs( cellBills1[i] - cellBills2[i] ) > ) isEqual = false; // elements are not equal } See Example 8.8 ComparingArrays.java 8

enum Types We discussed enumerations earlier in a previous lecture. Here is a review again: – Enumerated Types are classes with special properties. – They have a finite number of instances (as for example Days in previous slide). 9

Useful enum Methods 10 Return valueMethod name and argument list intcompareTo( Enum eObj ) compares two enum objects and returns a negative number if this object is less than the argument, a positive number if this object is greater than the argument, and 0 if the two objects are equal. intordinal( ) returns the numeric value of the enum object. By default, the value of the first object in the list is 0, the value of the second object is 1, and so on. booleanequals( Object eObj ) returns true if this object is equal to the argument eObj; returns false otherwise String toString( ) returns the name of the enum constant

Example enum enum PersonType { ADULT_MALE, CHILD_MALE, ADULT_FEMALE, CHILD_FEMALE }; public class Persons { PersonType pt; String firstName; static int id; int currentid; public Persons() { firstName="John"; id++; currentid=id; } public void setPersonType(PersonType pertyp) { this.pt=pertyp; } public PersonType getPersonType() { return pt; } 11

Example enum public class PersonsClient { public static void main(String[] args) { Persons p1=new Persons(); Persons p2=new Persons(); p1.setPersonType(PersonType.ADULT_FEMALE); p2.setPersonType(PersonType.CHILD_MALE); System.out.println("p1 is of person type:"+" "+p1.getPersonType()); System.out.println("p2 is of person type:"+" "+p2.getPersonType()); } 12

Example enum – Output – p1 is of person type: ADULT_FEMALE – p2 is of person type: CHILD_MALE – Notice that enumeration is a class: – It can be included in the same file as the class that is using it (the service class) or – It can be by itself in its own file in which case you have to compile it. 13

Algorithms An algorithm is any set of detailed instructions which results in a predictable end-state from a known beginning. – We can program the instructions to achieve a specific result – For example, we may want to develop a technique for searching arrays to find if a specific piece of data is store din the array and in which index is stored. – Another example is the case where we want to store the values stored in an array in some predefined order. 14

Sequential Search A Sequential Search can be used to determine if a specific value (the search key) is in an array. Approach Start with the first element and compare each element to the search key: – If found, return the index of the element that contains the search key – If not found, return -1 Because -1 is not a valid index, this is a good return value to indicate that the search key was not found in the array 15

Code to Perform a Sequential Search Suppose we want to search array: int numbers[] for a number of value key: public int sequentialSearch ( int key ) { for ( int i = 0; i < numbers.length; i++ ) { if ( numbers[i] == key ) return i; } return -1; } 16

Example Suppose numbers={ 3, 5, 1, 6, 10, 2 } and key=6 i=0 is 6==3 ? No i=1 is 6==5 ? No i=2 is 6==1 ? No i=3 is 6==6 ? Yes return index=3 (found it) i=4 is 6==10? No i=2 is 6==2 ? No Notice that the algorithm keeps going even after the key is found until all elements of the array are compared. 17

Revised Code for more efficient search public int sequentialSearch( int key ) { for ( int i = 0; numbers[i] <= key && i < numbers.length; i++ ) { if ( numbers[i] == key ) return i; } return –1; // end of array reached without finding key or // an element larger than the key was found } Notice that the for loop stops when the key is found because of the condition numbers[i] <= key ! 18

Sorting an Array When an array's elements are in random order, our Sequential Search method needs to look at every element in the array before discovering that the search key is not in the array. This is inefficient; the larger the array, the more inefficient a Sequential Search becomes. We could simplify the search by arranging the elements in numeric order, which is called sorting the array. Once the array is sorted, we can use various search algorithms to speed up a search. 19

Sequential Search of a Sorted Array When the array is sorted, we can implement a more efficient algorithm for a sequential search. If the search key is not in the array, we can detect that condition when we find a value that is higher than the search key. All elements past that position will be greater than the value of that element, and therefore, greater than the search key. 20

Selection Sort Suppose we want to sort from smallest to largest element in the array. In a Selection Sort, we make one pass through the array and select the largest element in the array and place it at the end of the array. Then we make another pass through the array up to index=length-2 this time and select the next-largest element and put it in the next-to-last position in the array, and so on. To do this, we consider the unsorted portion of the array as a subarray. – We repeatedly select the largest value in the current subarray and move it to the end of the subarray, then consider a new subarray by eliminating the elements that are in their sorted locations. – We continue until the subarray has only one element. At that time, the array is sorted. 21

The Selection Sort Algorithm To sort an array with n elements in ascending order: 1. Consider the n elements as a subarray with m = n elements 2. Find the index of the largest value in this subarray 3. Swap the values of the element with the largest value and the element in the last position in the subarray 4. Consider a new subarray of m = m - 1 elements by eliminating the last element in the previous subarray 5. Repeat steps 2 through 4 until m = 1 22

Selection Sort Example In the beginning, the entire array is the unsorted subarray : We swap the largest element with the last element: 23

Selection Sort Example (cont’d) Again, we swap the largest element and the last element : When there is only one unsorted element, the array is completely sorted: 24

Sorting Arrays of Objects In arrays of objects, the array elements are object references. Thus, to sort an array of objects, we need to sort the data of the objects. Usually, one of the instance variables of the object acts as a sort key. – For example, in an object, the sort key might be the date received. 25

Code for Selection Sort Declarations import java.util.*; import java.io.*; public class SelectionSort { public static void main(String[] args) { int i=0; int count=0; int index=0; int array []=new int[10]; int temp; int max; int subarraylength=0; //notice that we have assumed that there are 10 numbers in the file. //otherwise we have to count the numbers in the file and set the size of //the array accordingly. 26

Code for Selection Sort– Read the numbers from a file and place in array Notice that we have assumed that we know the size of the file (the number of numbers)!!! try { File file=new File(args[0]); Scanner scanner=new Scanner(file); i=scanner.nextInt(); array[count]=i; //first element at index 0 has been entered. while(scanner.hasNext()) { count++; i=scanner.nextInt(); array[count]=i; } catch (IOException e){System.out.println(“Error reading the file”); } 27

Code for Selection Sort– Algorithm //we are going to go through the array size-1 times. for (int j=0; j<=array.length-1; j++ ) { subarraylength=array.length-j; //find index of largest element in subarray index=0; for (int k=1; k<subarraylength; k++) { if (array[k] > array[index]) { index=k; } 28

Code for Selection Sort– Algorithm // Now swap array elements temp=array[index]; array[index]=array[array.length-j-1]; array[array.length-j-1]=temp; }//end top for //Read the array now. The elements should be sorted. for (int g=0; g<array.length ; g++) { System.out.println(+array[g]); } }//end main }// end of class 29

Sorting Objects By a Field’s Value Change the comparison from the previous slides so that it is now: If(array[k].getFieldName()>array[index].getFieldName()) ………………………………….. Be careful with the swapping part of the algorithm also.. – temp variable will have to be of the class type that is stored in the array i.e VehicleA temp; 30

Number of Comparisons Suppose the unsorted array size= n First pass (comparisons) is n-1 Next pass is n-2 Next pass is n-3 and so on. Total number of passes (comparisons) is: n ( n-1) / 2 Thus if n=10 numbers of passes: 10*(10-1)/2 = 45 31