Saturday, July 19, 2014

Sequential Search Algorithm using Java

Sequential Search is simplest algorithm. You try to search given element in given collections sequentially and return only if you found element.



Java Program using Sequential Search Algorithm :
package com.anuj.algorithms;

/**
 * 
 * @author Anuj
 * @source goldenpackagebyanuj.blogspot.com
 */
public class SequentialSearch {

    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5, 19, 17, 7};

        int searchItem = 3;
        SequentialSearch sequentialSearch = new SequentialSearch();
        boolean searchItemFound = sequentialSearch.contains(a, searchItem);
        System.out.println("SearchItem " + searchItem + " found : " + searchItemFound);
    }

    public boolean contains(int[] a, int searchItem) {
        for (int i : a) {
            if (i == searchItem) {
                return true;
            }
        }
        return false;
    }
}

Output :
SearchItem 3 found : true
BUILD SUCCESSFUL (total time: 0 seconds)

No comments:

Post a Comment