Showing posts with label Algo. Show all posts
Showing posts with label Algo. Show all posts
 

Searching algorithms - Binary Search

Binary Search is a Divide and Conquer algorithm. In Divide and Conquer, we reduce a larger problem into smaller subproblems recursively until the problem is small enough that the solution is trivial.

A important condition for Binary Search is that the array should be a sorted array. If the array is sorted in ascending order, Binary Search compares the target element with the middle element of the array. If the target element matches, then it returns true. Otherwise, if the target is less than the middle element then it will recurse on the sub-array to the left of the middle element or if the item is greater then it will recurse on the sub-array to the right of the middle element. So, at each step the size of array will be reduced to half. After repeating this recursion, it will eventually be left with a single element.

Pseudo code or binary search:
Algorithm BinarySearch(Array, left, right, target) 
{
    if left is less than or equal to right then :
        mid = (left + right) / 2
        if Array[mid] is equal to target
            return true
        else if item is less than Array[mid] 
            recurse on the left subarray
        else if item is greater than Array[mid] 
            recurse on the right subarray
    else
        return false
}
Note: Array has to be sorted for Binary Search to work.

Binary Search can be implemented in two ways i.e recursive and iterative.

1. Iterative code:
bool BinarySearchIter(int arr[], int length, int target) 
{
    int left = 0, right = length - 1, mid;
    while (left <= right) 
    {
        /* positon of middle element */
        mid = left + (right - left) / 2;

        /* element is found */
        if (arr[mid] == target)
            return true;

        /* searching on left sub-array */
        else if (item < A[mid])
            right = mid - 1;   

        /* searching on right sub-array */
        else
            left = mid + 1;
    }
    /* element not found */
    return false;
}
2. Recursive code:
bool BinarySearchRecur(int arr[], int left, int right, int target) 
{
    if (left <= right) 
    {
        /* positon of middle element */
        int mid = left + (right - left) / 2;

        /* element is found */
        if (arr[mid] == target)
            return true;

        else if (item < arr[mid])
        {
            /* recursve call on the left sub-array */
            return BinarySearchRecur(arr, left, mid-1, target);        
        }

        else
        {
             /* recursive call on the right sub-array */
             return BinarySearchRecur(arr, mid+1, right, target);     
        }
   }
   else
        /* element not found */
        return false;
}
Time complexity of Binary Search is O(logN) where N is the size of the array. This is because after each recursion or each iteration the size of problem is reduced into half.

Explaining with a example:

Let array Arr = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} and we need to find 3 in array Arr. So target = 3 and length = 10


Initially,
left = 0, right = length – 1 = 10 – 1 = 9
In 1st iteration,
mid = left + (right – left) / 2 = 0 + (9 – 0) / 2 = 4
Arr[mid] ( = 4) is greater than item. Since the array A is sorted we can say that the item must be in the left sub-array.


So now,
left = 0, right = mid – 1 = 4 – 1 = 3
In 2nd iteration,
mid = left + (right – left) / 2 = 0 + (3 – 0) / 2 = 1
Arr[mid] ( = 1) is smaller than item. Since the array A is sorted we can say that the item must be in the right sub-array.

So now,
left = mid + 1 = 1 + 1 = 2, right = 3
In 3rd iteration,
mid = left + (right – left) / 2 = 2 + (3 – 2) / 2 = 2
Arr[mid] ( = 2) is smaller than item. Since the array A is sorted we can say that the item must be in the right sub-array.


So,
left = mid + 1 = 2 + 1 = 3, right = 3
In 4th iteration,
mid = left + (right – left) / 2 = 3 + (3 – 3) / 2 = 3
A[mid] ( = 3) is equal to the target, so the Binary Search function will return true and the element is found.
 

Searching algorithms - Linear Search

Linear search, also sometimes referred as brute-force search or sequential search is one of the simplest search algorithms. It starts with checking if the first element of a list matches the target and continues on for each element of the list till a match is found or the end of the list is reached. For linear search, a data structure like an array or linked list is generally in play. Collections that are only accessible via an iterator are also good candidates for linear search.
The best case is O(1) i.e the target element at first position. The worst case when the element is at the last position is O(n). The average case is also O(n). The code for implementing a linear search is simple.
public static bool LinearSearch(int[] arr, int target)
{
    for (int i = 0; i < arr.Length; i++)
    {
        if (arr[i] == target)
            return true;
    }
    return false;
}

Why use sequential search?

  • If your collection size is relatively small and you would be performing this search relatively a few times, then this might an option. 
  •  Another case is when you need to have constant insertion performance (like using a linked list) and the search frequency is less. 
  •  In addition, linear search places very few restrictions on the complex data types. All that is needed is a match function of sorts.
Linear Search Optimizations

If the elements you would be searching in a list are NOT uniformly distributed, then you could do certain optimizations that can help you improve the efficiency of your search algorithms. For such improvements to be effective, you do need to know the characteristics of the data being searched, the frequency and also the fact that the underlying collection needs to be modifiable. 
  • Most Recently Used pattern: If the likelihood of the current element being searched again is high, then move if from it's current location (say position i) to the front of the collection (say position 0). This does require moving elements from A[0, i-1] to A[1, i] to accommodate the new element at A[0]. 
  •  The disadvantage of the above pattern is that it requires a lot of movement. One quick strategy is to move an element up on success by simply swapping the target element from position x with the first element at position 0. This eventually results in a similar pattern as the frequently searched elements bubble up to the top of the list. 
  • On the other end of the spectrum, if an element is unlikely to be search again, then moving it to the end on find improves the chances of the other elements being searched.