searching Concept: Linear search Binary search We have a list or array of items We want to determine if a particular key is in the list Linear search Search items, one by one On average each search considers half of the list Binary search The list must be in sorted Each search requires log2 list size compares
Linear search code private boolean linearSearch (Comparable[] data, Comparable which) { for (int i=0; i<data.length; i++) if (data[i].compareTo(which)==0) return true; } return false;
Binary Search code private boolean binarySearch(Comparable[] data, Comparable which) { int low=-1, high = data.length, middle, compare; while (low+1<high) middle = (low + high)/2; compare = data[middle].compareTo(which); if (compare==0) return true; else if (compare<0) low = middle; else high =middle; } return false;
Generic search code Linear Search private boolean genericSearch(ArrayList dataList, Comparable which) { return (dataList.contains(which)) ? true: false; } Binary Search return (Collections.binarySearch(dataList, which)>=0)? true: false;