/** * LinearSearch * * This class is used to search an int array * for a particular key. Linear search is okay for * small amounts of data. However, once the data becomes * large the amount of time to compare elements to a key value * becomes unacceptable. * @author Brad Rippe * @version 1.0 */ public class LinearSearch { /** * This is the main method */ public static void main(String[] args) { int[] testArray = new int[50]; testArray[43] = 10; int testArray2[] = { 35, 23, 8, 34, 66, 88, 5, 2, 85, 33 }; System.out.println("Searching for element == 10"); System.out.println("Element found at " + linearSearch(testArray, 10)); System.out.println("Searching the second array for element == 88"); System.out.println("Element found at " + linearSearch(testArray2, 88)); } /** * This method searches for a key value in an array. * @param array the integer array to be searched. * @param key the key value to find * @return the subscript of the key if found, otherwise -1 */ public static int linearSearch(int[] array, int key) { for(int i = 0; i < array.length; i++) { if(array[i] == key) return i; } return -1; } }