Searching in Java

Searching is a common operation in coding world. In searching we are provided with an array or list and we have to search some element in that list or array.

We are going to look at few algorithms and inbuilt Java methods to perform searching :

  1. Linear Searching
  2. Inbuilt methods of Java for searching
  3. Binary Search

Linear Searching

In this we are given an array and we simply scan the array elements one by one until we obtain the desired element being searched. Let us look at the code example :

public class Tech4Humans {

	static int linearSearch(int[] arr, int elem) 
	{
		int indexOfElement = -1;
		int arrLength = arr.length;
		for (int i = 0; i < arrLength; i++) 
		{
			if (arr[i] == elem) 
			{
				indexOfElement = i;
				break;
			}
		}
		return indexOfElement;
	}

	public static void main(String[] args) 
	{

		int arr[] = { 23, 12, 45, 33, 223, 21, 45, 67, 54, 32 };

		int indexOfElement = linearSearch(arr, 67);
		if (indexOfElement == -1) 
		{
			System.out.println("Element not found");
		} 
		else 
		{
			System.out.println("Element found at index : " + indexOfElement);
		}
	}

}

Output

Element found at index : 7

Inbuilt methods

In Java we can use inbuild methods of ArrayList to search any element in the list. We can use indexOf() or contains() method of ArrayList to perform searching. Let us look at an example code:

import java.util.ArrayList;

public class BruteForceSearch {

	public static void main(String[] args) 
	{
		ArrayList<Integer> arrList =new ArrayList<Integer>();
		arrList.add(20);
		arrList.add(30);
		arrList.add(454);
		arrList.add(54);
		arrList.add(32);
		arrList.add(98);
		
		int indexOfElement = arrList.indexOf(54);
		
		if (indexOfElement == -1) 
		{
			System.out.println("Element not found");
		} 
		else 
		{
			System.out.println("Element found at index : " + indexOfElement);
		}
	}

}

Output

Element found at index : 3

Leave a Comment