Searching Algorithms in Java

Rohit Goyal's Blog

  1. Linear Search
  2. Binary Search

Linear Search

Linear Search is the simplest search algorithm that consists of checking every one of its elements, one at a time and in sequence, until the desired one is found. It doesn’t require the collection to be sorted.

For a list with n items, the best case is when the value is equal to the first element of the list, in which case only one comparison is needed. The worst case is when the value is not in the list (or occurs only once at the end of the list), in which case n comparisons are needed.

It is having timing complexity with is O(n)


public int linerSearch(int[] data, int key){
         
        int size = data.length;
        for(int i=0;i<size;i++){
            if(data[i] == key){
                return i;
            }
        }
        return -1;
    }

Binary Search

Binary Search or half-interval search requires the array to be sorted and it can only be…

View original post 283 mots de plus

Publicités
Par défaut