Java Search Algorithms - Linear Search

Guest Posts Paolo Nikko Nuñal

When it comes to Data Structures, it is important to know some searching algorithms. In this tutorial we are going to learn on the many types of searching algorithms. The first one in our list is one of the basic when it comes to finding something whether it is a string or an integer. Linear Search, from the name itself is a "one direction" or linear in nature.

This algorithm is useful if you are looking for "something" .

public class LinearSearchAlgorithm {
 public static void main(String[] args)
 {
 System.out.println("Items in Array");
 System.out.println("[A, Z, E, F, G, B, I, M, Z, K]");
 String[] ArrayString = {"A", "Z", "E", "F", "G", "B", "I", "M", "Z", "K"};
 
 int i;
 String search = "F";
 boolean flag=false;
 
 for(i =0; i < ArrayString.length; i++)
 {
 if(ArrayString[i] == search)
 {
 flag = true;
 }
 }
 if(flag){
 System.out.println(search + " is found in the array.");
 }
 else{
 System.out.println(search + " not found in the array");
 }
 
 } 
}


From the program above, we are creating a linear search. The first thing we did is we populated the array with letters. After which, we loop through every elements of the array one-by-one and compared it with the item that we would like to search. The flag variable will be the one responsible for "trapping" if the element is found on the array. Otherwise the program will return with an error indicating it is not found.