import java.util.ArrayList; import java.util.List; public class Searching { /** * Tests whether the given list contains the given element. * * @param list a list * @pre. list != null * @param element an element * @return true if the given list contains the given element, * false otherwise. */ public static boolean contains(List list, Integer element) { boolean contains; if (list.isEmpty()) // base case { contains = false; } else // recursive case { List rest = new ArrayList(list.subList(1, list.size())); contains = list.get(0).equals(element) || Searching.contains(rest, element); } return contains; } /** * Tests whether the sublist of the given list starting * at the given index contains the given element. * * @param list a list * @pre. list != null * @param element an element * @param index begin index of the sublist * @pre. index <= 0 && index <= list.size() * @return true if the sublist of the given list * starting at the given index contains the given element, * false otherwise. */ public static boolean contains(List list, Integer element, int index) { boolean contains; if (index == list.size()) // base case: sublist is empty { contains = false; } else // recursive case: sublist is nonempty { contains = list.get(0).equals(element) || Searching.contains(list, element, index + 1); } return contains; } /** * Tests whether the sublist of the given list specified * by the given start and end index contains the given element. * * @param list a list * @pre. list != null && list is sorted * @param element an element * @param begin begin index of the sublist * @param end end index of the sublist * @pre. begin <= 0 && begin <= end && end <= list.size() * @return true if the sublist of the given list * specified by the given start and end index contains * the given element, false otherwise. */ public static boolean contains(List list, Integer element, int begin, int end) { boolean contains; if (begin >= end) // base case: sublist is empty { contains = false; } else // recursive case: sublist is nonempty { int middle = (begin + end) / 2; int comparison = element.compareTo(list.get(middle)); if (comparison == 0) // element found in the middle { contains = true; } else if (comparison < 0) // element smaller than element in the middle { contains = Searching.contains(list, element, begin, middle); } else // element larger than element in the middle { contains = Searching.contains(list, element, middle + 1, end); } } return contains; } }