Search Algorithm using JAVA

Rajendra Mahato
Oct 24, 2020
  1. Linear Search
  2. Binary Search
  3. Jump Search
  4. Interpolation Search
  5. Exponential Search
  6. Sublist Search (Search a linked list in another list)
  7. Fabonacci Search
  8. The Ubiquitous Binary Search
Linear Search

Linear Search :

A linear search scans one item at a time, without jumping to any item. The worst case complexity is O(n), sometimes known as O(n) search. Time taken to search elements keep increasing as the number of elements are increased. Linear search is less used today because it is slower than binary search and hashing.

A simple approach to do a linear search, i.e

  • Start from the left most element of array[] and one by one compare x with each element of array[].
  • If x matches with an element, return the index.
  • If x doesn’t match with any of element, return -1;
Linear search : Find 74

Linear search example :

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println(“Enter the size of array”);

int arr_size = scanner.nextInt();

System.out.println(“Enter array element”);

int[] arr = new int[arr_size];

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

arr[i] = scanner.nextInt();

}

System.out.println(“Please enter the search element”);

int search_element = scanner.nextInt();

int result = Search(arr, search_element);

if (result == -1){

System.out.println(“Search element not available”);

}else{

System.out.println(“Search element is in index = “+result);

}

scanner.close();

}

private static int Search(int[] arr, int x){

int arr_length = arr.length;

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

if (arr[i] == x){

return i;

}

}

return -1;

}

In the next article we will get to know about Binary Search.

GitHub link for linear search example

Follow me on GitHub for more data structure and algorithm code examples.

THANK YOU!!!

--

--

Rajendra Mahato
0 Followers

Full stack android developer | Dhanbad | Bangalore, India