Array: Linear Search

package Array;

/**
 * Created by aarushi on 1/5/21.
 */
public class ArrayLinearSearch {

    public static boolean linearSerach (int [] array, int key){
        //In Linear Search, we traverse the entire array to search for the key
        //The linear search method compares the key with each element in the array.
        //If the key is not found, then the function returns false
        for(int i=0; i<array.length; i++){
            if (array[i]==key){
                return true;
            }
        }

        return false;
    }

    public static void main (String [] args){
        System.out.println(linearSerach(new int[] {1,2,3,4,5}, 4));
        System.out.println(linearSerach(new int[] {1,2,3,4,5}, -1));
        System.out.println(linearSerach(new int[] {1,2,3,4,5}, 2));
    }
}

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.