1 / 21

Lecture 3 Linear Search and Binary Search ArrayLists

CS 202 John Hurley. Lecture 3 Linear Search and Binary Search ArrayLists. Searching is the process of looking for a specific element in a data structure; for example, discovering whether a certain score is included in a list of scores.

Download Presentation

Lecture 3 Linear Search and Binary Search ArrayLists

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS 202 John Hurley Lecture 3Linear Search and Binary SearchArrayLists

  2. Searching is the process of looking for a specific element in a data structure; for example, discovering whether a certain score is included in a list of scores. Searching is a common task in programming. There are many algorithms and data structures devoted to searching. In this section, two commonly used approaches are discussed, linear search and binary search. Searching Arrays and Lists

  3. The linear search approach compares the key element, key, sequentially with each element in an array or list. The method continues to do so until the key matches an element in the list or the list is exhausted without a match being found. If a match is made, the linear search returns the index of the element that matches the key. If no match is found, the search returns -1. Linear Search

  4. animation Linear Search Animation Key List 3 3 3 3 3 3

  5. /** The method for finding a key in the list */ public static int linearSearch(int[] list, int key) { for (int i = 0; i < list.length; i++) if (key == list[i]) return i; return -1; } From Idea to Solution Trace the method int[] list = {1, 4, 4, 2, 5, -3, 6, 2}; int i = linearSearch(list, 4); // returns 1 int j = linearSearch(list, -4); // returns -1 int k = linearSearch(list, -3); // returns 5

  6. For binary search to work, the elements in the array must already be ordered. Without loss of generality, assume that the array is in ascending order. e.g., 2 4 7 10 11 45 50 59 60 66 69 70 79 The binary search first compares the key with the element in the middle of the array. Binary Search

  7. If the key is less than the middle element, you only need to search the key in the first half of the array. If the key is equal to the middle element, the search ends with a match. If the key is greater than the middle element, you only need to search the key in the second half of the array. Binary Search, cont. Consider the following three cases:

  8. animation Binary Search Key List 8 8 8

  9. Binary Search, cont.

  10. Binary Search, cont.

  11. The binarySearch method returns the index of the element in the list that matches the search key if it is contained in the list. Otherwise, it returns -insertion point - 1. The insertion point is the point at which the key would be inserted into the list. Binary Search, cont.

  12. /** Use binary search to find the key in the list */ public static int binarySearch(int[] list, int key) { int low = 0; int high = list.length - 1; while (high >= low) { int mid = (low + high) / 2; if (key < list[mid]) high = mid - 1; else if (key == list[mid]) return mid; else low = mid + 1; } return -1 - low; } From Idea to Soluton

  13. Since binary search is frequently used in programming, Java provides several overloaded binarySearch methods for searching a key in an array of int, double, char, short, long, and float in the java.util.Arrays class. For example, the following code searches the keys in an array of numbers and an array of characters. int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79}; System.out.println("Index is " + java.util.Arrays.binarySearch(list, 11)); char[] chars = {'a', 'c', 'g', 'x', 'y', 'z'}; System.out.println("Index is " + java.util.Arrays.binarySearch(chars, 't')); For the binarySearch method to work, the array must be pre-sorted in increasing order. The Arrays.binarySearch Method Return is 4 Return is –4 (insertion point is 3, so return is -3-1)

  14. The Arrays.sort Method Since sorting is frequently used in programming, Java provides several overloaded sort methods for sorting an array of int, double, char, short, long, and float in the java.util.Arrays class. For example, the following code sorts an array of numbers and an array of characters. double[] numbers = {6.0, 4.4, 1.9, 2.9, 3.4, 3.5}; java.util.Arrays.sort(numbers); char[] chars = {'a', 'A', '4', 'F', 'D', 'P'}; java.util.Arrays.sort(chars); The sort algorithm used depends on the parameter type

  15. Lists • Need to import java.util.List as well as whatever specific type of list you use, egjava.util.ArrayList • A List must be a list of values of some other data type, in the same way that an array is an array of items of some other type. List are parameterized by the data type of the values in the list. • Unlike an array, a list can only contain objects, not primitive types. For example, you can not declare a list of doubles, but you can declare a list of Doubles. You will understand this better in a couple of weeks. • We show the underlying data type by enclosing it in angle braces, for example: • List <String>

  16. List Methods • The List class provides many methods you will need to use with lists. Here are some easy to understand ones. • add() adds an item to the end of the list • get(int position) gets a reference to the item at the specified position in the list • isEmpty() returns a boolean that indicates just what it sounds like • size() shows the number of items in the list • clear() deletes all items from the list

  17. Array List • importjava.util.List; • importjava.util.ArrayList; • publicclass Demo { • publicstaticvoid main(String args[]) { • // create the list • List<Integer> myList = newArrayList<Integer>(); • // add items to the list • for(int counter = 0; counter < 10; counter++) • myList.add(counter); • // print the items in the list • for(Integer i: myList) • System.out.println(i); • // add another item to the list, then print • myList.add(10); • for(Integer i: myList) • System.out.println(i); • // delete an item from the list, then print • myList.remove(0); • for(Integer i: myList) • System.out.println(i); • } // end main() • }

  18. More List Methods • Some List methods hinge on the fact that a List contains elements of some other data type. • contains(Object o) • indexOf(Object o) finds the index of the first occurrence of a value in the list • lastIndexOf(Object o) finds the index of the last occurrence of a value in the list

  19. More List Methods • publicstaticvoid main(String args[]) { • List<Double> myList = newArrayList<Double>(); • List<Double> testList = newArrayList<Double>(); • finaldouble PI = 3.14159; • doublefToCFactor = 5.0/9.0; • doublebodyTemperature = 98.6; • myList.add(PI); • myList.add(fToCFactor); • MyList.add(PI); • testList.add(PI); • testList.add(fToCFactor); • testList.add(bodyTemperature); • for(Double d: testList) • System.out.println(myList.contains(d)?("The first occurrence of " + d + " in myList is at position "+ myList.indexOf(d) + • " and the last occurrence is at " + myList.lastIndexOf(d)): • "myList does not contain " + d); • } // end main()

  20. Age Guess import javax.swing.JOptionPane; public class BetterGuess { public static void main(String[] args) { int tries = 0; int high = 100; int low = 0; int guess; int direction; do { guess = (high + low) / 2; String[] choices = { "Older", "This Old", "Younger" }; direction = JOptionPane.showOptionDialog(null, "Are you " + guess + "?", "Age Guess", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, choices, "Age Guess"); if (direction == 0) low = guess + 1; // last guess was too low if (direction == 2) high = guess - 1; // last guess was too high tries++; } while (direction != 1); System.out.println("Guessed in " + tries + " tries"); } } 22

  21. You should be able to explain in one sentence how any method you write works. If you can’t, break it down into two or more methods. Write and Test Your Code Incrementally The Stevie Wonder principle: "When you believe in things that you don't understand, then you suffer."

More Related