linear search


See On Github

Data

Tags

linear, search

Source Code

import java.util.Scanner;

public class LinearSearch {

    protected static int linearSearch(int arrayToBeSearched[], int numberToBeSearched) {

        int valueFound = -1;
        for(int loopVariable=0;loopVariable<arrayToBeSearched.length;loopVariable++) {

            if(numberToBeSearched == arrayToBeSearched[loopVariable]) {
                valueFound = loopVariable;
                break;
            }
        }
        return valueFound;
    }

    public static void main(String args[]) {

        Scanner scannerObject = new Scanner(System.in);

        System.out.println("Enter the size of array");
        int sizeOfArray = scannerObject.nextInt();

        int arrayOfElements[] = new int[sizeOfArray];

        System.out.println("Enter the elements in the array");
        for(int loopVariable = 0;loopVariable<sizeOfArray;loopVariable++) {
            arrayOfElements[loopVariable] = scannerObject.nextInt();
        }

        System.out.println("Enter the element to be searched");
        int elementToBeSearched = scannerObject.nextInt();

        int valueFound = linearSearch(arrayOfElements,elementToBeSearched);
        if(valueFound == -1)
            System.out.println("Notfound");
        else
            System.out.println("Found !!");

    }
}




import static org.junit.Assert.*;
import org.junit.Test;

public class LinearSearchTest {

    @Test
    public void TestLinearSearch() {

        int testArray[] = {1,2,3,4,5,6}; 
        int testElement1 = 4; 
        int testElement2 = 0;
	int testElement3 = 33;

        LinearSearch objectForLinearSearch = new LinearSearch();
        int testSearch1 = objectForLinearSearch.linearSearch(testArray,testElement1);
        int testSearch2 = objectForLinearSearch.linearSearch(testArray,testElement2);
	int testSearch3 = objectForLinearSearch.linearSearch(testArray,testElement3);

        assertEquals(testSearch1,3);
        assertEquals(testSearch2,-1);
	assertEquals(testSearch3,-1);
    }
}