1 Lecture 23 Searching Overview  What is Searching?  Linear Search and its Implementation.  Brief Analysis of Linear Search.  Binary Search and its.

Slides:



Advertisements
Similar presentations
Zabin Visram Room CS115 CS126 Searching
Advertisements

Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
Copyright © 2012 Pearson Education, Inc. Chapter 8: Searching and Sorting Arrays.
HST 952 Computing for Biomedical Scientists Lecture 9.
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 Lecture 21 Introduction to Sorting I Overview  What is Sorting?  Some Useful Array Handling Methods.  Selection Sort and its Implementation.  Brief.
1 ICS103 Programming in C Lecture 14: Searching and Sorting.
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 Searching Algorithms Overview  What is Searching?  Linear Search and its Implementation.  Brief Analysis of Linear Search.  Binary Search and its.
1 Search & Sorting Using Java API Searching and Sorting Using Standard Classes  Searching data other than primitive type.  Comparable interface.  Implementing.
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.
Searching Arrays Linear search Binary search small arrays
Searching Chapter 18 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Searching Chapter Chapter Contents The Problem Searching an Unsorted Array Iterative Sequential Search Recursive Sequential Search Efficiency of.
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.
1 Sorting Algorithms (Part I) Sorting Algoritms (Part I) Overview  What is Sorting?  Some Useful Array Handling Methods.  Selection Sort and its Implementation.
1 CSC 222: Computer Programming II Spring 2005 Searching and efficiency  sequential search  big-Oh, rate-of-growth  binary search  example: spell checker.
Chapter 8 ARRAYS Continued
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 14: Sorting and searching. Chapter Goals To study several sorting and searching algorithms To appreciate that algorithms for the same task can.
Dictionaries CS 105. L11: Dictionaries Slide 2 Definition The Dictionary Data Structure structure that facilitates searching objects are stored with search.
CS 46B: Introduction to Data Structures July 7 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Building Java Programs Chapter 13 Searching reading: 13.3.
CPT: Search/ Computer Programming Techniques Semester 1, 1998 Objectives of these slides: –to discuss searching: its implementation,
Search - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 19/23/2015.
Copyright © 2012 Pearson Education, Inc. Chapter 8: Searching and Sorting Arrays.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Sorting and Searching.
1 Searching. 2 Searching Searching refers to the operation of finding an item from a list of items based on some key value. Two Searching Methods (1)
SEARCHING UNIT II. Divide and Conquer The most well known algorithm design strategy: 1. Divide instance of problem into two or more smaller instances.
DATA STRUCTURE & ALGORITHMS (BCS 1223) CHAPTER 8 : SEARCHING.
CSC 205 Java Programming II Algorithm Efficiency.
Advance Data Structure 1 College Of Mathematic & Computer Sciences 1 Computer Sciences Department م. م علي عبد الكريم حبيب.
CS 162 Intro to Programming II Searching 1. Data is stored in various structures – Typically it is organized on the type of data – Optimized for retrieval.
SEARCHING. Vocabulary List A collection of heterogeneous data (values can be different types) Dynamic in size Array A collection of homogenous data (values.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Searching Course Lecture Slides 28 May 2010 “ Some things Man was never.
Searching. Linear (Sequential) Search Search an array or list by checking items one at a time. Linear search is usually very simple to implement, and.
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.
90-723: Data Structures and Algorithms for Information Processing Copyright © 1999, Carnegie Mellon. All Rights Reserved. 1 Lecture 9: Searching Data Structures.
CSC 211 Data Structures Lecture 13
1 ICS103 Programming in C Lecture 14: Searching and Sorting.
“Enthusiasm releases the drive to carry you over obstacles and adds significance to all you do.” – Norman Vincent Peale Thought for the Day.
Data Structures Using C++ 2E Chapter 9 Searching and Hashing Algorithms.
Data Structure Introduction.
ITEC 2620M Introduction to Data Structures Instructor: Prof. Z. Yang Course Website: ec2620m.htm Office: Tel 3049.
Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure.
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.
Dictionaries CS /02/05 L7: Dictionaries Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Data Structures and Algorithms Searching Algorithms M. B. Fayek CUFE 2006.
Binary search and complexity reading:
Lecture 8: Advanced OOP Part 2. Overview Review of Subtypes Interfaces Packages Sorting.
1. Searching The basic characteristics of any searching algorithm is that searching should be efficient, it should have less number of computations involved.
Dictionaries CS 110: Data Structures and Algorithms First Semester,
CS 116 Object Oriented Programming II Lecture 4 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
 Introduction to Search Algorithms  Linear Search  Binary Search 9-2.
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.
ICS103 Programming in C Lecture 14: Searching and Sorting
Searching Given a collection and an element (key) to find… Output
Lecture 14: binary search and complexity reading:
searching Concept: Linear search Binary search
Lecture 15: binary search reading:
Sorting and Searching -- Introduction
Searching.
ICS103: Programming in C Searching, Sorting, 2D Arrays
Presentation transcript:

1 Lecture 23 Searching Overview  What is Searching?  Linear Search and its Implementation.  Brief Analysis of Linear Search.  Binary Search and its Implementation.  Brief Analysis of Binary Search.  Searching and Sorting Real Data.  Using Standard Searching and Sorting Methods.

2 Lecture 23 What is Searching?  Searching means scanning through a list of items or records to find if a particular one exists.  It usually requires the user to specify the target item (or a target key e.g. id_no, name, etc.)  If the target item is found, the item or its location is returned, otherwise, an appropriate message or flag (example –1) is returned.  Like sorting, an important issue in processing a search request is response time.  This depends on factors similar to those that affect sorting such as:  The size of the list  The data structure used; array, linked-list, binary tree  The organization of data; random or ordered  We restrict our discussion to methods for lists represented as arrays.

3 Lecture 23 Linear Search and its Implementation  This involves searching through the list sequentially until the target item is found or the list is exhausted.  If the target is found, its location is returned, otherwise a flag such as –1 is returned.  The following implements Linear Search. public class LinearSearch { public static int search(int[] a, int v) { for (int i = 0; i < a.length; i++) { if (a[i] == v) return i; } return -1; }

4 Lecture 23 Linear Search and its implementation (cont’d) 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); System.out.println("Enter number to search for:"); int n = Integer.parseInt(console.readLine()); int j = search(a, n); if (j != -1) System.out.println("Found in position " + j); else System.out.println(n + " not found"); }

5 Lecture 23 Brief Analysis of Linear Search  For a list of n elements, the linear search takes an average of n/2 comparisons to find an item, with the best case being 1 comparison and the worst case being n comparisons.  However, if the list is ordered, it is a waste of time to look for an item using linear search (it would be like looking for a word in a dictionary sequentially). In this case we apply binary search, which we discuss next.

6 Lecture 23 Binary Search and its Implementation  Binary search works by comparing the target with the item at the middle of the list. This leads two one of three results:  The middle item is the target – we are done.  The middle item is less than the target – we apply the algorithm to the upper half of the list.  The middle item is bigger than the target – we apply the algorithm to the lower half of the list.  This process is repeated until the item is found or the list is exhausted.  The following implements this approach.

7 Lecture 23 Binary Search and its Implementation (cont’d) import java.io.*; public class BinarySearch { public static int binarySearch(int[] a, int from, int to, int v) { if (from > to) return -1; int mid = (from + to) / 2; int diff = a[mid] - 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(int[] a, int 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)); int[] a=ArrayUtil.randomIntArray(20, 100); SelectSort.sort(a); ArrayUtil.print(a); System.out.println("Enter number to search for:"); int n = Integer.parseInt(console.readLine()); int j = search(a, n); System.out.println("Found in position " + j); }

8 Lecture 23 Binary Search

9 Lecture 23 Binary Search

10 Lecture 23 Brief Analysis of Binary Search Binary search is by far more efficient than linear search. – the number of comparisons required is on the average log 2 (n).  Thus, for a list of 1000 items, binary search requires only log 2 (1000)  10, whereas linear search requires 1000/2 = 500. The difference gets more dramatic with larger lists as the following table shows.  Binary search has one problem -- it is only applicable to ordered data. Thus, there is an additional overhead of sorting which can be very significant.  We shall experiment the efficiency of the various sorting/searching discussed so far in the Lab, but the following table should give an idea. Array sizeLog 2 NNN Log 2 NN2N , ,536 1,000101,00010,0001 million 100, , million10 billion

11 Lecture 23 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:

12 Lecture 23 Searching and Sorting Real Data (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 }

13 Lecture 23 Searching and Sorting Real Data (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"); }}

14 Lecture 23 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");

15 Lecture 23 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"); }