Website For Developers

Searching in Java



Linear Search in Java

Process of Linear Search


Example of linear search in Java

import java.util.Scanner;
public class LinearSearch {

   public static void main(String args[]) {
     int[] array = {10, 20, 30, 40, 50};
     int check = -1;
     System.out.println( "Enter value to find" );
     Scanner scan = new Scanner(System.in);
     int value = scan.nextInt();

     for (int i = 0; i < array.length; i++) {
       if (array[i] == value) {
         check = i;
      }
    }
    if (check == -1) {
       System.out.println( "Value is not found in the array." );
    }
    else {
       System.out.println( "Value is found." );
    }
  }
}

Output

Enter value to find
40
Value is found.


Binary Search in Java


Example of binary search in Java

import java.util.Scanner;
public class BinarySearch {

   public static void main(String args[]) {
     int[] array = {10, 22, 31, 35, 48, 99};
     int check = -1;
     int mid;
     int first = 0, last = 6;
     System.out.println( "Enter value to find" );
     Scanner scan = new Scanner(System.in);
     int value = scan.nextInt();

     while (first <= last) {
       mid = (first + last) /2;
       if (array[mid] == value) {
         check = mid;
         break;
       }
       else if (value < array[mid]) {
         last = mid - 1;
       }
       else {
         first = mid + 1;
       }
     }

     if (check == -1){
       System.out.println( "Value is not found in the array." );
     }
     else {
       System.out.println( "Value is found." );
     }
  }
}

Output

Enter value to find
99
Value is found.