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; }