## Linear Search Program in Java

Category : Data-structures-algorithms | Sub Category : Search Algorithms | By Prasad Bonam Last updated: 2020-11-05 10:03:28 Viewed : 290

# Linear Search:

Linear search is the easiest search algorithm It works with sorted and unsorted arrays (an binary search works only with sorted array)

This algorithm just compares all elements of an array to find a value

Worst-case performance O(n)

Best-case performance O (1)

Average performance O(n)

Example 1:

LinearSearch .java

`package runnerdev; `

import java.util.Scanner;

public class LinearSearchEx {

public static int linearSearch(int array[], int num) {

int len = array.length;

for (int i = 0; i < len; i++) {

if (array[i] == num)

return i;

}

return -1;

}

public static void main(String args[]) {

int array[] = { 12, 13, 40, 100, 140 };

Scanner sc = new Scanner(System.in);

System.out.println("Enter number : ");

int num = sc.nextInt();

int result = linearSearch(array, num);

if (result == -1)

System.out.print("Given number is not present in array");

else

System.out.print("Given number is present at index: " + result);

}

}

Output:

Enter number :

40

Given number is present at index: 2

Example 2: Pick the element randomly using java8

LinearSearch .java

` public class LinearSearch { `

/**

* Generic Linear search method        *

* @param array List to be searched

* @param value Key being searched for

* @return Location of the key

*/

public <T extends Comparable<T>> int find(T[] array, T value) {

for (int i = 0; i < array.length; i++) {

if (array[i].compareTo(value) == 0) {

return i;

}

}

return -1;

}

public static void main(String[] args) {

// just generate data

Random r = new Random();

int size = 200;

int maxElement = 100;

Integer[] integers =

Stream.generate(() -> r.nextInt(maxElement)).limit(size).toArray(Integer[]::new);

// the element that should be found

Integer shouldBeFound = integers[r.nextInt(size - 1)];

LinearSearch search = new LinearSearch();

int atIndex = search.find(integers, shouldBeFound);

System.out.println(

String.format(

"Should be found: %d. Found %d at index %d. An array length %d",

shouldBeFound, integers[atIndex], atIndex, size));

}

}

Output:

Should be found: 87. Found 87 at index 81. An array length 200