// APS101, Winter 2009: Lecture 36 (Apr. 7) // // Review: last time we covered the basics of Exception Handling. // throwing an exception: throw new Exception(); throw new NullPointerException("A message that describes the problem."); // we wrote our own custom exception: TTTException e = new TTTException(); e e.getMessage() // catching an exception: // use the try-catch block that we learned in lecture last time. // Now, we will consider two search algorithms. // first, assume that the list (array of ints) is in no particular order. // Ex. int[] list = {11, 2, 8, 9, 0, 3}. // we want to search for an element x in the list. // if x is found in the list, return the index of x in list. // if x is not found in the list, return -1. // Ex. if x = 8, then the method should return 2 (8's position in list). // can you think of a simple algorithm to perform this task? // (go through list sequentially and compare x with every element). // this is called Linear Search... see method linearSearch in Search.java Search.linearSearch(new int[]{1, 5, 99, 54, 43, 3}, 54) // returns 3 Search.linearSearch(new int[]{1, 5, 99, 54, 43, 3}, 55) // returns -1 // if there are duplicate elements in the list, the method returns the // index of the first element that is found. Search.linearSearch(new int[]{1, 5, 99, 54, 54, 43, 3}, 54) // still returns 3 // however, this is not the most efficient algorithm... // what if x is found at the very end of the list? or not found at all? // in the worst case, the algorithm would have to make N comparisons, // where N is the number of elements in the list. // this is bad, because there could be millions of elements in the list. // there is a better way to search. // first, the list must be sorted in ascending order. // then, we can use the sorted property of the list to search for x faster. // (see the PDF file with the Binary Search example) // (also see method binarySearch in Search.java) Search.binarySearch(new int[]{5, 23, 45, 99, 200}, 45) // returns 2 Search.binarySearch(new int[]{5, 23, 45, 99, 200}, 46) // returns -1 Search.binarySearch(new int[]{5, 23, 45, 99, 200}, 200) // returns 4 Search.binarySearch(new int[]{5, 23, 45, 99, 200}, 5) // returns 0 Search.binarySearch(new int[]{5, 23, 45, 99, 200}, 1) // returns -1 Search.binarySearch(new int[]{5, 23, 45, 99, 200}, 250) // returns -1