/** * Implements two search algorithms: linear search and binary search * * @author alchambers * @version Fall 2015 */ public class Searching { /** * Uses linear search algorithm to find the index of k in a given array * @param array the array to be searched * @param k the value to find * @return the index of k in the array or -1 if k does not occur */ public static int linearSearch(int[] array, int k){ for(int i = 0; i < array.length; i++){ if(array[i] == k){ return i; } } return -1; } /** * Uses binary search algorithm to find the index of k in a given array * PRE-CONDITION: Assumes the input array is sorted * * @param array the array to be searched * @param k the value to find * @return the index of k in the array or -1 if k does not occur */ public static int binarySearch(int[] array, int k){ int left = 0; int right = array.length-1; while(left <= right){ int mid = (left+right)/2; if(k == array[mid]){ return mid; // we found the index of k in the array } // Search for k in the upper half else if(k > array[mid]){ left = mid + 1; } // Search for k in the lower half else { right = mid - 1; } } // The value k does not occur in the array return -1; } }