ICS201 Lecture 20 : Searching King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.

Slides:



Advertisements
Similar presentations
Zabin Visram Room CS115 CS126 Searching
Advertisements

Sorting. “Sorting” When we just say “sorting,” we mean in ascending order (smallest to largest) The algorithms are trivial to modify if we want to sort.
CS 206 Introduction to Computer Science II 09 / 10 / 2008 Instructor: Michael Eckmann.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 11: Sorting and Searching  Searching Linear Binary  Sorting.
CIS 101: Computer Programming and Problem Solving Lecture 6 Usman Roshan Department of Computer Science NJIT.
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.
Chapter 11 Sorting and Searching. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Examine the linear search and.
Searching Chapter Chapter Contents The Problem Searching an Unsorted Array Iterative Sequential Search Recursive Sequential Search Efficiency of.
Quicksort. Quicksort I To sort a[left...right] : 1. if left < right: 1.1. Partition a[left...right] such that: all a[left...p-1] are less than a[p], and.
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.
Quicksort.
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 © 2006 Pearson Addison-Wesley. All rights reserved Searching and Sorting Linear Search Binary Search ; Reading p Selection Sort ; Reading p
Searching/Sorting Introduction to Computing Science and Programming I.
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.
Searching1 Searching The truth is out there.... searching2 Serial Search Brute force algorithm: examine each array item sequentially until either: –the.
1 © 2006 Pearson Addison-Wesley. All rights reserved Searching and Sorting Linear Search Binary Search -Reading p
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Comparing Objects in Java. The == operator When you define an object, for instance Person p = new Person("John", 23); we talk about p as if its value.
Chapter 8 ARRAYS Continued
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.
(c) University of Washingtonhashing-1 CSC 143 Java Hashing Set Implementation via Hashing.
CS 46B: Introduction to Data Structures July 7 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Chapter 5 Ordered List. Overview ● Linear collection of entries  All the entries are arranged in ascending or descending order of keys.
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
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.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
Copyright © 2013 by John Wiley & Sons. All rights reserved. SORTING AND SEARCHING CHAPTER Slides by Rick Giles 14.
Chapter 19 Searching, Sorting and Big O
Non-static classes Part 2 1. Methods  like constructors, all non-static methods have an implicit parameter named this  for methods, this refers to the.
1 Searching and Sorting Linear Search Binary Search.
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.
Chapter 9 Searching and Sorting
CS 61B Data Structures and Programming Methodology July 28, 2008 David Sun.
CSC 211 Data Structures Lecture 13
SortingBigOh ASFA AP Computer Science A. Big-O refers to the order of an algorithm runtime growth in relation to the number of items I. O(l) - constant.
Chapter 5 Searching and Sorting. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine the linear search and binary.
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.
CS261 Data Structures Ordered Bag Dynamic Array Implementation.
HashCode() 1  if you override equals() you must override hashCode()  otherwise, the hashed containers won't work properly  recall that we did not override.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Selection Sort Sorts an array by repeatedly finding the smallest.
Symbol Tables From “Algorithms” (4 th Ed.) by R. Sedgewick and K. Wayne.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Computer Science 101 Fast Algorithms. What Is Really Fast? n O(log 2 n) O(n) O(n 2 )O(2 n )
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,
Visual C++ Programming: Concepts and Projects Chapter 8A: Binary Search (Concepts)
Binary search and complexity reading:
ICS201 Lecture 21 : Sorting King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
1. Searching The basic characteristics of any searching algorithm is that searching should be efficient, it should have less number of computations involved.
Data Structures Arrays and Lists Part 2 More List Operations.
CMPT 120 Topic: Searching – Part 2 and Intro to Time Complexity (Algorithm Analysis)
Searching Arrays Linear search Binary search small arrays
Searching.
Searching.
Adapted from Pearson Education, Inc.
Lecture 14: binary search and complexity reading:
Lecture 15: binary search reading:
Searching CLRS, Sections 9.1 – 9.3.
Searching.
Searching.
Presentation transcript:

ICS201 Lecture 20 : Searching King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department

The Problem Searching is an every day occurrence. Searching a particular item among a collection of many items

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 final int NONE = -1; // not a legal index static int linearSearch(int target, int[] a) { for (int p = 0; p < a.length; p++) { if (target == a[p]) return p; } return NONE; }

Searching an array of Strings Searching an array of Strings is just like searching an array of integers, except Instead of i1==i2 we need to use s1.equals(s2) static final int NONE = -1; // not a legal index static int linearSearch(String target, String[] a) { for (int p = 0; p < a.length; p++) { if (target.equals(a[p])) return p; } return NONE; }

Searching an array of Objects Searching an array of Objects is just like searching an array of Strings, provided The operation equals has been defined appropriately static final int NONE = -1; // not a legal index static int linearSearch(Object target, Object[] a) { for (int p = 0; p < a.length; p++) { if (target.equals(a[p])) return p; } return NONE; }

Java review: equals The Object class defines public boolean equals(Object obj) For most objects, this just tests identity: whether the two objects are really one and the same This is not generally what you want The String class overrides this method with a method that is more appropriate for Strings You can override equals for your own classes But there are some rules you should follow if you do

Overriding equals If you override equals, your method should have the following properties (for your objects x, y, z ) Reflexive: for any x, x.equals(x) should return true Symmetric: for any non-null objects x and y, x.equals(y) should return the same result as y.equals(x) Transitive: if x.equals(y) and y.equals(z) are true, then x.equals(z) should also be true Consistent: x.equals(y) should always return the same answer (unless you modify x or y, of course) For any non-null x, x.equals(null) should return false Java cannot check to make sure you follow these rules

About sorted arrays An array is sorted in ascending order if each element is not smaller than the preceding element An array is sorted in descending order if each element is no larger than the preceding element When we just say an array is “ sorted, ” by default we mean that it is sorted in ascending order An array of Object cannot be in sorted order ! There is no notion of “ smaller ” or “ larger ” for arbitrary objects We can define an ordering for some of our objects

The Comparable interface java.lang provides a Comparable interface with the following method: public int compareTo(Object that) This method should return A negative integer if this is less than that Zero if this equals that A positive integer if this is greater than that Reminder: you implement an interface like this: class MyObject implements Comparable { public int compareTo(Object that) {...} }

Consistency with equals compareTo is consistent with equals if: x.compareTo(y)==0 gives the same boolean result as x.equals(y ) Therefore: if you implement Comparable, you really should override equals as well Java doesn ’ t actually require consistency with equals, but sooner or later you ’ ll get into trouble if you don ’ t meet this condition

Binary Search Ignoring one-half of the data when the data is sorted.

Binary search Linear search has linear time complexity: Time n if the item is not found Time n/2, on average, if the item is found If the array is sorted, we can write a faster search How do we look up a name in a phone book, or a word in a dictionary? Look somewhere in the middle Compare what ’ s there with the thing you ’ re looking for Decide which half of the remaining entries to look at Repeat until you find the correct place This is the binary search algorithm

Binary search algorithm To find which (if any) component of a[left..right] is equal to target (where a is sorted): Set l = left, and set r = right While l <= r, repeat: Let m be an integer about midway between l and r If target is equal to a[m], terminate with answer m If target is less than a[m], set r = m–1 If target is greater than a[m], set l = m+1 Terminate with answer none lrmm-1m+1 ?

Binary search in Java static int binarySearch(Comparable target, Comparable[] a, int left, int right) { int l = left, r = right; while (l <= r) { int m = (l + r) / 2; int comp = target.compareTo(a[m]); if (comp == 0) return m; else if (comp < 0) r = m – 1; else /* comp > 0 */ l = m + 1; } return NONE; // As before, NONE = -1 }

Recursive binary search in Java static int binarySearch(Comparable target, Comparable[] a, int left, int right) { if (left > right) return NONE; int m = (left + right) / 2; int comp = target.compareTo(a[m]); if (comp == 0) return m; else if (comp < 0) return binarySearch(target, a, left, m-1); else // comp > 0 return binarySearch(target, a, m+1, right); }

Java Class Package: The Method binarySearch The class Arrays in java.util defines versions of a static method with following specification: /** Task: Searches an entire array for a given item. array the array to be searched desiredItem the item to be found in the array index of the array element that equals desiredItem; * otherwise returns -belongsAt-1, where belongsAt is * the index of the array element that should contain * desiredItem */ public static int binarySearch(type[] array, type desiredItem);

The Method binarySearch

Binary search takes log n time In binary search, we choose an index that cuts the remaining portion of the array in half We repeat this until we either find the value we are looking for, or we reach a subarray of size 1 If we start with an array of size n, we can cut it in half log 2 n times Hence, binary search has logarithmic (log n) time complexity For an array of size 1000, this is 100 times faster than linear search ( 2 10 ~= 1000 )

Conclusion Linear search has linear time complexity Binary search has logarithmic time complexity For large arrays, binary search is far more efficient than linear search However, binary search requires that the array be sorted If the array is sorted, binary search is 100 times faster for an array of size times faster for an array of size This is the kind of speedup that we care about when we analyze algorithms

The end