OBJECT ORIENTED PROGRAMMING II LECTURE 4 GEORGE KOUTSOGIANNAKIS

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Lesson 8 Searching and Sorting Arrays 1CS 1 Lesson 8 -- John Cole.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
Arrays in Java Selim Aksoy Bilkent University Department of Computer Engineering
Searching and Sorting Arrays
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Data Structures Using C++ 2E
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.
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.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 12 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
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 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.
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 21 GEORGE KOUTSOGIANNAKIS
Searching and Sorting Searching algorithms with simple arrays
UNIT - IV SORTING By B.Venkateswarlu Dept of CSE.
Sorts, CompareTo Method and Strings
Searching and Sorting Arrays
Alternate Version of STARTING OUT WITH C++ 4th Edition
OBJECT ORIENTED PROGRAMMING I LECTURE 10 GEORGE KOUTSOGIANNAKIS
Subject Name: Design and Analysis of Algorithm Subject Code: 10CS43
OBJECT ORIENTED PROGRAMMING II LECTURE 23 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING I LECTURE 7 GEORGE KOUTSOGIANNAKIS
Lecture 14 Searching and Sorting Richard Gesick.
Introduction to Search Algorithms
OBJECT ORIENTED PROGRAMMING I LECTURE 12 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 15 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 2 GEORGE KOUTSOGIANNAKIS
CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II
OBJECT ORIENTED PROGRAMMING II LECTURE 2_1 GEORGE KOUTSOGIANNAKIS
Chapter 7 Part 1 Edited by JJ Shepherd
Design and Analysis of Algorithms
OBJECT ORIENTED PROGRAMMING I LECTURE 7 GEORGE KOUTSOGIANNAKIS
Linear and Binary Search
Building Java Programs Chapter 7
Describing algorithms in pseudo code
Introduction to Programming
Chapter 8 Search and Sort
Outline Late Binding Polymorphism via Inheritance
Lecture 11 Searching and Sorting Richard Gesick.
Searching and Sorting Arrays
Standard Version of Starting Out with C++, 4th Edition
Building Java Programs
Searching and Sorting 1-D Arrays
25 Searching and Sorting Many slides modified by Prof. L. Lilien (even many without an explicit message indicating an update). Slides added or modified.
24 Searching and Sorting.
Sub-Quadratic Sorting Algorithms
OBJECT ORIENTED PROGRAMMING II LECTURE 13_1 GEORGE KOUTSOGIANNAKIS
Sorting "There's nothing in your head the sorting hat can't see. So try me on and I will tell you where you ought to be." -The Sorting Hat, Harry Potter.
OBJECT ORIENTED PROGRAMMING II LECTURE 22 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING I LECTURE 5 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 13_2 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
Suggested self-checks: Section 7.11 #1-11
Searching and Sorting Arrays
Dr. Sampath Jayarathna Cal Poly Pomona
Arrays.
Presentation transcript:

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

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

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

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

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

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: Instantiate an array with the new size and a temporary name Copy the original elements to the new array Point the original array reference to the new array Assign a null value to the temporary array reference

Comparing Arrays for Equality To compare whether the elements of two arrays are equal: Determine if both arrays have the same length 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.

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] ) > 0.001 ) isEqual = false; // elements are not equal } See Example 8.8 ComparingArrays.java

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

Useful enum Methods Return value Method name and argument list int compareTo( 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. ordinal( ) 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. boolean equals( 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 public class Persons { PersonType pt; String firstName; 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;

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

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.

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.

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

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;

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.

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 !

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.

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.

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.

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

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

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:

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 email object, the sort key might be the date received.

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.

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++; array[count]=i; } catch (IOException e){System.out.println(“Error reading the file”); }

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

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

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;

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