Friday, March 26, 2010

Linear Search Java Example

Below is linear Searching Algorithm implemented in Java.



import java.util.Scanner;

//##################################################
// Linear Search
//##################################################
//Program has list of integers saved in an array and
//program will take inputs from user and search that
//if that input is present in Array of Integers.

public class linearSearch {

public static void main(String args[]) {

int[] listOfIntegers = { 1, 34, 53, 23, 77, 98, 101, 20, 45, 66, 84 };
int inputTobeSearch;

Scanner sn = new Scanner(System.in);
inputTobeSearch = sn.nextInt();
int token = -1;

for (int i = 0; i < listOfIntegers.length; i++) {

if (listOfIntegers[i] == inputTobeSearch) {
token = i;
}
}

if (token != (-1)) {
System.out
.println("Input integer " + inputTobeSearch
+ " is present at " + (token + 1)
+ "th place in the Array");
} else
System.out.println("Input integer " + inputTobeSearch
+ " is not present in the Array");

}

}

No comments: