Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "1 Lecture 23 Searching Overview  What is Searching?  Linear Search and its Implementation.  Brief Analysis of Linear Search.  Binary Search and its."— Presentation transcript:

1 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 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 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 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 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 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 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 8 Lecture 23 Binary Search

9 9 Lecture 23 Binary Search

10 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 NN2N2 8382464 1287 89616,384 2568 204865,536 1,000101,00010,0001 million 100,00017100,0001.7 million10 billion

11 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 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 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 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 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"); }


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

Similar presentations


Ads by Google