CodesJava

Easy learning with example program codes

Java linear search program using recursion


Search algorithm

Search algorithm refers to a step-by-step procedure which is used to locate specific data among a collection of data. All search algorithms use a search key in order to proceed for the search operation. The efficiency of a search algorithm is measured by the number of times a comparison of the search key is done in the worst case. The notation used in search algorithms is O(n), where n is the number of comparisons done.

Linear search

Linear search is a way of finding a target value within a collection of data. It is also known as sequential search. It sequentially checks each element of the collection data for the target value until a match is found or until all the elements have been searched.

Example

package com.codesjava;
 
public class Test {
     public static int recSearch(int data[], int l, int r, int key) {
        if (r < l)
           return -1;
        if (data[l] == key)
           return l;
        return recSearch(data, l+1, r, key);
    }
 
    public static void main(String args[]){
	int[] data= {50,27,30,50,70,9,19};    
        int key = 9;    
 
        int index = recSearch(data, 0, data.length-1, key);
        if (index != -1)
           System.out.println("Element " + key + " is present at index " + index);
        else
            System.out.println("Element " + key + " is not present");
    }
}

Output

9 is found at index: 5


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap