Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.

Slides:



Advertisements
Similar presentations
11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
Advertisements

Recursion Chapter 14. Overview Base case and general case of recursion. A recursion is a method that calls itself. That simplifies the problem. The simpler.
COMP 121 Week 9: AbstractList and ArrayList. Objectives List common operations and properties of Lists as distinct from Collections Extend the AbstractCollection.
CS 206 Introduction to Computer Science II 09 / 05 / 2008 Instructor: Michael Eckmann.
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Building Java Programs Chapter 13
 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
Garfield AP Computer Science
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Polymorphism. 3 Fundamental Properties of OO 1. Encapsulation 2. Polymorphism 3. Inheritance These are the 3 building blocks of object-oriented design.
Interfaces CSC 171 FALL 2004 LECTURE 14. Project 1 review public class Rational { private int numerator, denominator; public Rational(int numerator, int.
The Singleton Pattern II Recursive Linked Structures.
Java Review Interface, Casting, Generics, Iterator.
Exercise 1 Suppose C is a class that implements interfaces I and J. Which of the following Requires a type cast? C c = ……? I i = …..? J j = …..? c =
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Computer Science 209 Software Development Equality and Comparisons.
METHOD OVERRIDING Sub class can override the methods defined by the super class. Overridden Methods in the sub classes should have same name, same signature.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
1 Various Methods of Populating Arrays Randomly generated integers.
Collections Framework A very brief look at Java’s Collection Framework David Davenport May 2010.
1 SSD3 - Unit 2 Java toString & Equals Presentation Class Website:
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture22.
Using interfaces Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling How would you find the maximum.
1 Lecture 23 Searching Overview  What is Searching?  Linear Search and its Implementation.  Brief Analysis of Linear Search.  Binary Search and its.
Unit 261 Introduction to Searching and Sorting Comparable Interface Comparator Interface Algorithm Complexity Classes Exercises.
1 More on Inheritance Overview l Object: The father of all classes l Casting and Classes l Object Cloning l Importance of Cloning.
Searching Algorithms. Lecture Objectives Learn how to implement the sequential search algorithm Learn how to implement the binary search algorithm To.
Chapter 8 Search and Sort Asserting Java ©Rick Mercer.
CS 106 Introduction to Computer Science I 03 / 07 / 2008 Instructor: Michael Eckmann.
1 Search & Sorting Using Java API Searching and Sorting Using Standard Classes  Searching data other than primitive type.  Comparable interface.  Implementing.
1 Introduction to Searching and Sorting Comparable Interface -Reading p Comparator Interface.
Unit 261 Introduction to Searching and Sorting Comparable Interface Comparator Interface Algorithm Complexity Classes Exercises.
Introduction to Searching and Sorting
CSE 373 Data Structures and Algorithms Lecture 18: Hashing III.
COMP 14: Intro. to Intro. to Programming May 23, 2000 Nick Vallidis.
1 CSC 222: Computer Programming II Spring 2005 Searching and efficiency  sequential search  big-Oh, rate-of-growth  binary search  example: spell checker.
Searching Algorithms. The Search Problem Problem Statement: Given a set of data e.g., int [] arr = {10, 2, 7, 9, 7, 4}; and a particular value, e.g.,
Chapter 5 Ordered List. Overview ● Linear collection of entries  All the entries are arranged in ascending or descending order of keys.
Building Java Programs Chapter 13 Searching reading: 13.3.
CM0551 Exam Prep. What are an algorithm’s time and space complexity? (2 marks) Answer: The growth rate of the algorithm’s time requirement and the computer.
Teach.NET Workshop Series Track 4: AP Computer Science with.NET and J#
CS 106 Introduction to Computer Science I 03 / 19 / 2007 Instructor: Michael Eckmann.
Information and Computer Sciences University of Hawaii, Manoa
Lecture 8: Object-Oriented Design. 8-2 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Objectives “Good object-oriented programming is really.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
1 Linear and Binary Search Instructor: Mainak Chaudhuri
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
CSE 143 Lecture 15 Binary Search; Comparable reading: 13.2; 10.2 slides created by Marty Stepp
CS 206 Introduction to Computer Science II 09 / 10 / 2009 Instructor: Michael Eckmann.
ADSA: Generics/ Advanced Data Structures and Algorithms Objective –to describe basic forms of generic classes, interfaces, and methods for searching.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Interfaces and Inner Classes
Announcements Final Exam: TBD. Static Variables and Methods static means “in class” methods and variables static variable: one per class (not one per.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Data Structures in Java: From Abstract Data Types to the Java Collections.
CS 146: Data Structures and Algorithms June 11 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Chapter 3: Sorting and Searching Algorithms 3.1 Searching Algorithms.
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
Winter 2006CISC121 - Prof. McLeod1 Stuff We had better discuss a midterm date… –27 Feb. to 3 March or –6 to 10 March.
Day 3: The Command and Visitor Patterns. Preliminaries The Java static type system uses simple rules to infer types for Java expressions. The inferred.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
Building Java Programs Chapter 12: Recursive public/private pairs Chapter 13: Searching reading: 13.3.
Chapter 5 Ordered List.
Ch 14: Search and Sorting Yonglei Tao.
Introduction to Searching and Sorting
Chapter 5 Ordered List.
CSC 113: Computer programming II
Object Comparisons and Arrays
Creating and Modifying Text part 3
CMPE212 – Reminders Assignment 2 due next Friday.
Presentation transcript:

Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071

Searching Algorithm: Binary Search Java provides two binary search (02) methods: – Arrays.binarySearch (for an array) – Collections.binarySearch (for a List ) – Note that the values in the array / list are in sorted order. If they are not, binarySearch() method is not guaranteed to work properly.

Searching Algorithm: Binary Search (Cont’d)

Using Arrays.binarySearch() : int[] numbers = {-3, 2, 8, 12, 17, 29, 44, 79}; int index = Arrays.binarySearch(numbers, 29); System.out.println("29 is found at index " + index);

Searching Algorithm: Binary Search (Cont’d) Using Collections.binarySearch (for a List ) // binary search on ArrayList with the same values: int index = Collections.binarySearch(list, 29); System.out.println("29 is found at index " + index);

Sorting Algorithms: Merge Sort Algorithm Java provides two sorting methods: – Arrays.sort() (for an array) Arrays.sort(strings); – Collections.sort() (for a List )

Sorting Algorithms: Merge Sort Algorithm (Cont’d)

Using Arrays.sort () // demonstrate the Arrays.sort method String[] strings = {"c", "b", "g", "h", "d", "f", "e", "a"}; // Printing the strings before sorting…. System.out.println(Arrays.toString(strings)); Arrays.sort(strings); // Printing the strings after sorting…. System.out.println(Arrays.toString(strings)); – Output: [c, b, g, h, d, f, e, a] [a, b, c, d, e, f, g, h]

Sorting User-Defined Types Let’s assume we have an array of Student type objects that we want to sort. The type Student is defined as follows: class Student { private int id; public Student(int id) { this.id = id; } public int getId() { return id; } // other code follows… }

Sorting User-Defined Types (Cont’d) public class TestSort { public static void main(String[] args) { Student[] students = new Student[5]; students[0] = new Student(555555); students[1] = new Student(444444); students[2] = new Student(333333); students[3] = new Student(111111); students[4] = new Student(222222); System.out.println(Arrays.toString(students)); Arrays.sort(students); // Will this work? System.out.println(Arrays.toString(students)); }

Sorting User-Defined Types (Cont’d) The previous code compiles correctly. However, at runtime, we get the following exception: The method Arrays.sort() assumes that the class Student implements the Comparable interface!  ClassCastException

Sorting User-Defined Types (Cont’d) To fix this problem, let’s have the class Student implements the Comparable interface as follows: class Student implements Comparable { private int id; public Student(int id) { this.id = id; } public int getId() { return id; } // other code follows… // toString() method should be here public int compareTo(Object o) { if(o == null) throw new NullPointerException(); else { if(!(o instanceof Student)) throw new ClassCastException(); else { Student st = (Student) o; return id – st.getId(); } } // End of compareTo() method } // End of class Student

Sorting User-Defined Types Now the code is running correctly and the output should be:

Sorting User-Defined Types (Cont’d) Now, let’s revisit the compareTo() method: public int compareTo(Object o) { if(o == null) throw new NullPointerException(); else { if(!(o instanceof Student)) throw new ClassCastException(); else { Student st = (Student) o; return id – st.getId(); } } // End of compareTo() method Searching/Sorting based on id field! So to use Arrays.sort(), we have to restrict our comparison key on a single key!

Sorting User-Defined Types (Cont’d) To use different fields as keys for searching and sorting purposes, we have to use the following methods: Java provides two sorting methods: – Arrays.sort(Object[], Comparator) (for an array) using a specific Comparator object – Collections.sort(List, Comparator) (for a List ) using a specific Comparator object

Comparator Interface The Comparator (java.util) interface defines the following two methods: – int compare(Object o1, Object o2) – boolean equals(Object o)

Comparator Interface (Cont’d) Example: Let’s define a Comparator class to compare two Student objects based on the id field. class ComparatorId implements Comparator { public int compare(Object o1, Object o2) { if(o1 == null | o2 == null) throw new NullPointerException(); else { if(!(o1 instanceof Student) | !(o2 instanceof Student)) throw new ClassCastException(); else { Student st1 = (Student) o1; Student st2 = (Student) o2; return st1.getId() – st2.getId(); } } } // End of ComparatorId class

Comparator Interface (Cont’d) Important Note: The class ComparatorId implements the Comparator interface and it overrides only one method and the compiler does NOT complain! Answer: ?????

Sorting Using a Comparator object The code below illustrates the use of ComparatorId object for sorting purposes: import java.util.*; public class TestSort2 { public static void main(String[] args) { Student[] students = new Student[5]; students[0] = new Student(555555); students[1] = new Student(444444); students[2] = new Student(333333); students[3] = new Student(111111); students[4] = new Student(222222); System.out.println(Arrays.toString(students)); Arrays.sort(students, new ComparatorId()); System.out.println(Arrays.toString(students)); }

Comparator Interface (Cont’d) Drill Exercise: Now try to define a Comparator class to compare two Student objects based on the gpa field. class ComparatorGpa implements Comparator { public int compare(Object o1, Object o2) { } // End of ComparatorGpa class