How to do Linear Search in Java

Linear search is one of the simplest algorithms for searching data. In linear search, the entire data set is searched in a linear fashion for an input data. It is a kind of brute-force search and in the worst case scenario, the entire data set will have to be searched. Hence worst case cost is proportional to the number of elements in data set. The good thing about linear search is that the data set need not be ordered.

The following sample Java program demonstrates how linear search is performed to search a specific color in a list of colors. We sequentially take each color from the color list and compare with the color entered by the user. On finding the color, we immediately stop the iteration and print the results.

import java.util.Scanner;

/**
 * Example program in Java demonstrating linear search
 * @author 
 */
public class LinearSearchExample {
    private static final String[] COLOR_LIST = new String[] {
        "blue","red","green","yellow", "blue","white","black","orange","pink"
    };
    
    public static void main(String[] args) {
        System.out.println("Please enter a color to search for:");
        Scanner sn = new Scanner(System.in);
        String colorToSearch = sn.nextLine();
        
        LinearSearchExample ls = new LinearSearchExample();
        int position = ls.findColor(colorToSearch);
        if(position <0) {
            System.out.println("Sorry, the color is not found in the list");
        }else {
            System.out.println("Found color "+colorToSearch+" at position "+position);
        }             
    }

    /**
     * Demonstrates linear search in Java
     * Using linear search, looks up the color in a fixed list of colors
     * If color is found, the position is returned, else returns -1
     * Since linear search goes through entire list of elements in the worst case,
     * its cost is proportional to number of elements
     * @param colorToSearch
     * @return 
     */
    private int findColor(String colorToSearch) {
        int foundAt = -1;
        for(int i=0;i<COLOR_LIST.length;i++) {
            if(COLOR_LIST[i].equalsIgnoreCase(colorToSearch)) {
                foundAt = i;
                break;// found the color! no need to loop further!
            }
        }
        return foundAt;
    }
}