In this Post,we will talk and learn about How to Write a Java program for linear search using the Recursive Approach.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
package com.kkjavatutorials.client; import java.util.Scanner; /** * Java program for linear search using Recursive Approach * @author KK JavaTutorials * */ public class LinearSearchTest { public static void main(String[] args) { Scanner scanner = null; try { System.out.println("Enter input Array Size:"); scanner = new Scanner(System.in); int inputArraySize = scanner.nextInt(); int inputArray[] = new int[inputArraySize]; System.out.println("Enter " +inputArraySize+" Array Elements:"); for (int i = 0; i < inputArray.length; i++) { inputArray[i] = scanner.nextInt(); } System.out.println("Enter Seach Key Element:"); int seachKey = scanner.nextInt(); int startIndex = 0; int lastIndex = inputArraySize-1; int seachKeyIndex = linearSearch(inputArray,startIndex,lastIndex,seachKey); if( seachKeyIndex != -1) System.out.println(seachKey +" found at index: "+seachKeyIndex); else System.out.println(seachKey +" not found in inputArray"); } catch (Exception e) { e.printStackTrace(); }finally { if(scanner != null) scanner.close(); } } // linearSearch using recursive approach private static int linearSearch(int[] inputArray, int startIndex, int lastIndex, int seachKey) { if(lastIndex < startIndex) return -1; if(inputArray[startIndex] == seachKey) return startIndex; return linearSearch(inputArray,startIndex+1,lastIndex,seachKey); } } |
Some Sample input/output of the above Program:
Enter input Array Size:
5
Enter 5 Array Elements:
12
45
67
89
34
Enter Seach Key Element:
67
67 found at index: 2
Enter input Array Size:
4
Enter 4 Array Elements:
12
45
78
90
Enter Seach Key Element:
13
13 not found in inputArray
You May Also Like:
Reverse a string in Java (6 Different Ways)
Splitting a String in Java using a delimiter
Count number of words in a string java
Count total number of times each character appears in the string in java
Check if two strings are anagrams or not in java
How to convert string to int without using library functions in java
Check Whether a Given String/Number is a Palindrome in java
How to find first non-repeated character in a given String in Java
How to find first non-repeatable character from a String using Java 8
That’s all about How to Write a Java program for linear search using the Iterative Approach?
If you have any feedback or suggestion please feel free to drop in below comment box.