Skip to content

2.6 Basic Searching

Farrukh Ahmad edited this page Dec 15, 2015 · 1 revision

There are two way of basic searching

  1. Linear Search

  2. Binary Search [List must be sorted for this technique]

     public class Searching {
    
     public static void main(String[] args) {
     int a[] = {1,2,3,4,4,5};
     int key = 2;
     
     System.out.println(linearSearch(a, key));
     System.out.println(binarySearch(a, key));
    
     }
    
     static boolean linearSearch(int a[], int key){
     for(int i=0; i<a.length; i++){
     	if(a[i] == key)
     		return true;
     }
     return false;
     }
    
    
     static boolean binarySearch(int a[], int key){
     int low = 0;
     int high = a.length-1;
     
     while(low <= high){
     	int middle = low+high/2;
     	
     	if(a[middle] == key){
     		return true;
     	}
     	
     	if( key > a[middle]){
     		low = middle+1;
     	}
     	
     	if( key < a[middle]){
     		high = middle-1;
     	}
     }
     return false;
     }
     }
    

Clone this wiki locally