Searching
Searching is an operation which finds the location of a given element in a list. The search is said to be successful or unsuccessful depending on whether the element that is to be searched is found or not.
Linear Search
This is the simplest method of searching. In this method, the element to be searched is sequentially searched in the list. This method can be applied to a sorted or an unsorted list.
Searching in case of unsorted list starts from the 0th element and continues until the element is found or the end of list is reached.
LinearSearch1.java
class LinearSearch1{
public static void main(String[] args)
{
System.out.println(“Linear Search in an Unsorted List”);
int[] arr = {12, 9, 15, 98, 78, 65, 76, 54, 43, 3};
int i;
int num = 65;
boolean flag=false;
for(i=0; i<arr.length; i++){
if(arr[i]==num){
flag=true;
break;
}
}//for
if(flag){
System.out.println(num + ” is at position “+i);
}
else{
System.out.println(num + ” not found”);
}
}
}
//o/p- 65 is at position 5.