Linear Search in Java


 

Linear Search in Java

In this section, we are going to find an element from an array using Linear Searching. Basically it is used for small arrays.

In this section, we are going to find an element from an array using Linear Searching. Basically it is used for small arrays.

Linear Search in Java

In this section, we are going to find an element from an array using Linear Searching. Linear searching is a good way to find an element from the array. The array can be of any order, it checks whether a certain element (number , string , etc. ) is in a specified array or not. Basically it is used for small arrays. In the given code, we have allowed the user to enter the numbers to be stored into the arrays. If the element is found we can return the index where the element is located in the array. If the element is not found we can return -1.  

Here is the code:

import java.util.*;

public class LinearSearch {
	public int find(final int[] data, final int key) {
		for (int i = 0; i < data.length; ++i) {
			if (data[i] > key)
				return -1;
			else if (data[i] == key)
				return i;
		}
		return -1;

	}

	public static void main(String[] args) {
		final int arr[] = new int[10];
		System.out.println("Enter 10 numbers");
		Scanner input = new Scanner(System.in);
		for (int i = 0; i < arr.length; i++) {
			arr[i] = input.nextInt();
			}
		LinearSearch search = new LinearSearch();
		System.out.print("Enter the element to search: ");
		int num=input.nextInt();
		int n = search.find(arr, num);
		if ((n >= 0) && (n < arr.length)) {
			System.out.println("Found at index: " + n);
		} else {
			System.out.println("Not Found");
		}
	}

}

Output:


Enter 10 numbers:
1
2
3
4
5
6
7
8
9
10
Enter the element to search:5
Found at index: 4

Ads