1 Search & Sorting Using Java API Searching and Sorting Using Standard Classes  Searching data other than primitive type.  Comparable interface.  Implementing.

Slides:



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

IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture22.
Sorting Sorting places data in ascending or descending order, based on one or more sort keys E.g. A list of names could be sorted alphabetically, bank.
Sorting Algorithms: Merge and Quick. Lecture Objectives Learn how to implement the simple advanced sorting algorithms (merge and quick) Learn how to implement.
Lecture 27 Exam outline Boxing of primitive types in Java 1.5 Generic types in Java 1.5.
1 Lecture 23 Searching Overview  What is Searching?  Linear Search and its Implementation.  Brief Analysis of Linear Search.  Binary Search and its.
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-1: Arrays reading: 7.1 self-checks: #1-9 videos: Ch. 7 #4.
Searching. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
Searching and Sorting I 1 Searching and Sorting 1.
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.
1 Lecture 21 Introduction to Sorting I Overview  What is Sorting?  Some Useful Array Handling Methods.  Selection Sort and its Implementation.  Brief.
ICS201 Lecture 20 : Searching King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
1 More on 1-D Arrays Overview l Array as a return type to methods l Array of Objects.
Searching Algorithms. Lecture Objectives Learn how to implement the sequential search algorithm Learn how to implement the binary search algorithm To.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Searching. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
1 Searching Algorithms Overview  What is Searching?  Linear Search and its Implementation.  Brief Analysis of Linear Search.  Binary Search and its.
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.
Searching. Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
Introduction to Searching and Sorting
1 More on 1-D Array Overview l Array as a return type to methods l Array of Objects l Array Cloning l Preview: 2-D Arrays.
Sorting Arrays. Selection Sort  One of the easiest ways to sort the elements of an array is by using the selection sort algorithm.  Assume that the.
1 Sorting Algorithms (Part I) Sorting Algoritms (Part I) Overview  What is Sorting?  Some Useful Array Handling Methods.  Selection Sort and its Implementation.
Searching Also: Logarithms. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an.
CSC3170 Introduction to Database Systems
Chapter 14: Sorting and searching. Chapter Goals To study several sorting and searching algorithms To appreciate that algorithms for the same task can.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Fourteen: Sorting and Searching.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 13 – Sorting and Searching.
CS 46B: Introduction to Data Structures July 7 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Recursion A recursive computation solves a problem by using the solution of the same problem with simpler values The same computation occurs repeatedly.
Building Java Programs Chapter 13 Searching reading: 13.3.
Lecture 5 Searching and Sorting Richard Gesick. The focus Searching - examining the contents of the array to see if an element exists within the array.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Sorting and Searching.
Lecture 8: Object-Oriented Design. 8-2 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Objectives “Good object-oriented programming is really.
CHAPTER 18 SORTING AND SEARCHING. CHAPTER GOALS To study the several searching and sorting algorithms To appreciate that algorithms for the same task.
Algorithm Definition An algorithm is a step-by-step solution to a problem.
Java Arrays …………. Java Arrays …………. * arrays are objects in Java * arrays are objects in Java * an array variable is a reference * an array variable is.
CSE 143 Lecture 15 Binary Search; Comparable reading: 13.2; 10.2 slides created by Marty Stepp
Chapter 15: Algorithms 1 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 15 Algorithms.
INTERFACES More OO Concepts. Interface Topics Using an interface Interface details –syntax –restrictions Create your own interface Remember polymorphism.
Comparison-Based Sorting & Analysis Smt Genap
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Searching and Sorting.
Department of Computer Engineering Computer Programming for International Engineers I NTERNATIONAL S CHOOL OF E NGINEERING C HULALONGKORN U NIVERSITY.
CSI1390 – Java Programming Methods II Instructor: Saeid Nourian
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Review TEST 2 Chapters 4,5,7. QUESTION For which type of operands does the == operator always work correctly: (a) int, (b) double, or (c) String?
Building Java Programs Chapter 7 Arrays Copyright (c) Pearson All rights reserved.
Arrays. Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional  Java.
Arrays. Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional  Java.
Chapter 14 Sorting and Searching. Chapter Goals To study several sorting and searching algorithms To appreciate that algorithms for the same task can.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Sorting  Sorting places data in ascending or descending order, based on one or more sort.
Binary search and complexity reading:
Searching and Sorting 14ACEHRPT Copyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. Java Methods Object-Oriented.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
Building Java Programs Chapter 13 Searching and Sorting Copyright (c) Pearson All rights reserved.
3/21/2016IT 2751 Tow kinds of Lists Array What can be done? What can be easily done? student 1 student 2 student 3 student 4 Linked List student 2 student.
I/O in java and Revision. 2 I/O in Java Many packages and libraries associated with Java provide sophisticated ways to input and output information, e.g.:
Fibonacci Sequence Fibonacci sequence is a sequence of numbers defined by f 1 = 1 f 2 = 1 f n = f n-1 + f n-2 First ten terms – 1, 1, 2, 3, 5, 8, 13, 21,
EE2E1. JAVA Programming Lecture 4 Interfaces. Contents Interfaces – introduction Interfaces – introduction Example – generic sorting Example – generic.
Ch 14: Search and Sorting Yonglei Tao.
An Introduction to Java – Part I
Chapter 8: Collections: Arrays
Introduction to Searching and Sorting
Chapter 19 Sorting and Searching
Building Java Programs
មជ្ឈមណ្ឌលកូរ៉េ សហ្វវែរ អេច អ ឌី
Presentation transcript:

1 Search & Sorting Using Java API Searching and Sorting Using Standard Classes  Searching data other than primitive type.  Comparable interface.  Implementing compareTo() method.  java.util package & java.util.Arrays class.  Programming examples  Preview: Basic Data Structures (Part I).

2 Search & Sorting Using Java API Searching and Sorting Real Data  So far, all the algorithms we have studied have been on array of integers.  However, in real life, there is rarely a need to search or sort a collection of integers. What are often encountered are records of say students, bank accounts, books, etc., which have many fields.  In java, these records are implemented as objects. Thus, the question is, can we improve these algorithms to handle array of objects?  Fortunately Java has made it very easy to do this. All that is required is for a class to implement the Comparable interface which has one method named, compareTo(). Consider the following example:

3 Search & Sorting Using Java API Comparable Interface & compareTo() Method l java.lang package defines a Comparable interface as follows l public interface Comparable { int compareTo (Object other); } l Any class that implements the Comparable interface must supply the compareTo method l The compareTo method is intended to sort objects. A sorting algorithm will repeatedly call the compareTo method e.g. first.compareTo(second) depending on the return value (e.g. –1, 0, 1 ) from compareTo method, the sorting algorithm decides whether the objects are in correct order or not (sorting) OR the particular object is found or not (searching).

4 Search & Sorting Using Java API Example: Implementing of compareTo() method l Suppose we have a class Student and we want to search record of a particular student. The implementation of compareTo() method is as follows: l In compareTo() method object other of type Object is downcast to object s of type Student so that id of student to be search can be compare with id of other student. If search is successful the two ids matches and method returns 0. class Student implements Comparable { private int iDNumber; private String name; private double gPA; ….. public int compareTo(Object other ) { Student s = (Student) other ; if (iDNumber < s.iDNumber) return -1; else if (iDNumber > s.iDNumber) return 1; else return 0; }

5 Search & Sorting Using Java API Example: Implementing compareTo() (Cont’d) public class Student implements Comparable { private int iDNumber; private String name; private double gPA; public Student(int iDNumber, String name, double gPA) { this.iDNumber = iDNumber; this.name = name; this.gPA = gPA; } public Student(int iDNumber) { this(iDNumber,"",0.0); } public String toString() { return iDNumber+"\t"+name+"\t"+gPA; } public int compareTo (Object other) { Student s = (Student) other; if (iDNumber < s.iDNumber) return -1; else if (iDNumber > s.iDNumber) return 1; else return 0; } //other methods here }

6 Search & Sorting Using Java API Example: Implementing compareTo() (Cont’d) import java.io.*; public class ComparableSearch { public static int binarySearch(Comparable[] a, int from, int to, Comparable v) { if (from > to) return -1; int mid = (from + to) / 2; int diff = a[mid]. compareTo (v); if (diff == 0) // a[mid] == v return mid; else if (diff < 0) // a[mid] < v return binarySearch(a, mid + 1, to, v); else return binarySearch(a, from, mid - 1, v); } public static int search (Comparable[] a, Comparable v) { return binarySearch(a, 0, a.length - 1, v); } public static void main(String[] args) throws IOException { BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); Student[ ] s = new Student[4]; s[0] = new Student(955000, "Ibrahim", 3.5); s[1] = new Student(966000, "Amir", 2.0); s[2] = new Student(977000, "Talal", 2.4); s[3] = new Student(988000, "Usman", 2.5); for (int i = 0; i < s.length; i++) System.out.println(s[i]); System.out.print("\nEnter ID Number to search for:"); Comparable v = new Student(Integer.parseInt(console.readLine())); int j = search (s, v); if (j != -1) System.out.println("Found in position " + (j+1)); else System.out.println(v + " not found"); } }

7 Search & Sorting Using Java API Standard Sorting & Searching Methods  The Arrays class of the java.util package implements binarySearch and a sorting method for both numbers and comparable objects.  If you wish, you can call these methods rather than your own implementations.  The following example shows how these methods may be used. import java.io.*; import java.util. Arrays ; public class StandardSearch { public static void main(String[] args) throws IOException { BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); int[] a = ArrayUtil.randomIntArray(20, 100); ArrayUtil.print(a); Arrays.sort(a); ArrayUtil.print(a); System.out.print("\nEnter n number to search for:"); int j = Arrays.binarySearch(a, Integer.parseInt(console.readLine())); if (j != -1) System.out.println("Found in position " + (j+1)); else System.out.println("element not found");

8 Search & Sorting Using Java API Standard Sorting & Searching Methods (Cont’d) Student[] s = new Student[4]; s[0] = new Student(977000, "Talal", 2.4); s[1] = new Student(988000, "Usman", 2.5); s[2] = new Student(999000, "Umar", 3.0); s[3] = new Student(955000, "Ibrahim", 3.5); Arrays.sort(s); for (int i = 0; i < s.length; i++) System.out.println(s[i]); System.out.print("\nEnter ID Number to search for:"); Comparable v = new Student(Integer.parseInt(console.readLine())); j = Arrays.binarySearch(s, v); if (j != -1) System.out.println("Found in position " + (j+1)); else System.out.println(v + " not found"); } }

9 Search & Sorting Using Java API Modified ArrayUtil Class import java.util.Random; public class ArrayUtil { public static int[] randomIntArray(int length, int n) { int[] a = new int[length]; Random generator = new Random(); for (int i = 0; i < a.length; i++) a[i] = generator.nextInt(n); return a; } public static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } public static void swap( Comparable[] a, int i, int j) { Comparable temp = a[i]; a[i] = a[j]; a[j] = temp; } public static void print(int[] a) { for (int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); } public static Comparable[] copyArray(Comparable[] a, int size) { String[] b = new String[size]; if (size <= a.length) for (int i=0; i<size; i++) b[i] = (String) a[i]; return b; }