Linear search in java using recursion

Let’s learn linear search in java using recursion.

Linear search in java using recursion

In the below java program first user enters elements or numbers into the array using nextInt() method of Scanner class.

First we have to read length of given array and then read key value. Now we have to pass numbers, length and key value to linearRecursion() method.

linearRecursion() method returns index value. If index is not equal to -1 then key is found at index + 1 else key does not exist in array. Let’s see program on linear search using recursion.

import java.util.Scanner;
public class LinearSearchDemo 
{
   int linearRecursion(int[] arrNumber, int start, int last, int k)
   {
      if(last < start)
         return -1;
      if(arrNumber[start] == k)
         return start;
      return linearRecursion(arrNumber, start + 1, last, k);
   }
   public static void main(String[] args)
   {
      LinearSearchDemo obj = new LinearSearchDemo();
      int a, l, key, array[];
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter array length: ");
      l = sc.nextInt();
      array = new int[l];
      System.out.println("Please enter " + l + " elements");
      for(a = 0; a < l; a++)
      {
         array[a] = sc.nextInt();
      }
      System.out.println("Enter the search key value: ");
      key = sc.nextInt();
      int index = obj.linearRecursion(array, 0, l - 1, key);
      if(index != -1)
      {
         System.out.println(key + " is found at location " + (index + 1));
      }
      else
      {
         System.out.println(key + " doesn't exist in array.");
      }
      sc.close();
   }
}

Output:

Please enter array length: 6
Please enter 6 elements
15 25 35 55 75 95
Enter the search key value: 95
95 is found at location 6

Please enter array length: 6
Please enter 6 elements
15 25 35 55 75 95
Enter the search key value: 6
6 doesn’t exist in array.


Also read – while loop in java