3 Searching Algorithms You must kow

3 Searching Algorithms You must kow

What you will get from this blog post ?

If you are looking for a resource from which you can understand searching algorithms such as sequential search algorithm and interval search algorithm, then let me tell you that you are at the right place because in this blog post you will learn about the following things

  • What is the meaning of searching in the context of programming?
  • What are the different algorithms to do searching?
  • The practical implementation of searching algorithms with their time and space complexity

What is searching and what are the algorithms to do searching?

Searching basically means finding some element in the array or collection of elements . In order to do searching we have basically 3 different algorithms

  1. Sequential Search Algorithm
  2. Interval Search Algorithm
  3. Interpolation Search

Sequential Search Algorithm

Sequential search algorithm also known as the linear search algorithm is the simplest searching algorithm to search any target value in the array/group of elements. Basically, in a sequential search algorithm, we traverse through the whole of the array and check if the target value is present in our array or not, if present then we return the index of it and if not we return -1 , because -1 can never be the index.

R.gif

import java.util.*;

public class LinearSearch {
    public static void main(String[] args) throws Exception {

        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the size : ");
        int size = sc.nextInt();
        int[] arr = new int[size];

        System.out.println("Enter the values : ");
        for (int i = 0; i < arr.length; i++) {
            arr[i] = sc.nextInt();
        }

        System.out.print("Enter the target value : ");
        int target = sc.nextInt();

        // Call function to find the value
        int ans = find(arr, target);
        if (ans == -1) {
            System.out.println("Valut not found");
        } else {
            System.out.println("Value present at : " + ans);
        }

    }

    static int find(int[] arr, int target) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == target) {
                return i;
            }
        }
        // In case value not found
        return -1;
    }
}

Time and Space complextiy

In case of linear search algorihtm , the best case scenario would be the one where the target value which we are trying to find is present at the 0 index itslef, thus time it would take to compare values will be constant . But the worst case scenario would be the one where the target value which we are trying to find is not present in the array and we traversed through whole of the array.

Time complextiy (3).png

The space complexity of linear search algorithm is O(n) , where n is the total number of elements in the array.

Interval Search Algorithm

Interval search algorithm , which is also known as the binary search algorithm is more optimized searching algorithm for finding the target value in the array . Basically in the binary search algorithm we reduce the search space to find the target value , and the way we reduce the search space is by dividing the array into half and then selecting a particular half based on the target value and the order in which we want the array to be sorted.

One important thing to remember while implementing a binary search algorithm is that the array on which we want to implement the binary search algorithm, that array must be sorted either in ascending or descending order.

bePceUMnSG-binary_search_gif.gif

Time and Space complexity

In case of a binary search algorithm, the best case scenario would be the one where the target value which we are trying to find in the sorted array is present in the middle of the array itself , and since the time taken for doing comparison is always constant, thus the time complexity of binary search algorithm in the best case would also be constant.

SmartSelect_20220811-092800_Noteshelf.jpg

The space complexity of binary search algorithm, constant i.e. O(1)

import java.util.*;

public class LinearSearch {
    public static void main(String[] args) throws Exception {

        Scanner sc = new Scanner(System.in);
        int[] arr = { 1, 2, 3, 4, 5, 6 };

        System.out.print("Enter the target value : ");
        int target = sc.nextInt();

        // Call function to find the value
        int ans = find(arr, target);
        if (ans == -1) {
            System.out.println("Valut not found");
        } else {
            System.out.println("Value present at : " + ans);
        }

    }

    static int find(int[] arr, int target) {

        // First let's define the search space
        int start = 0;
        int end = arr.length - 1;
        while (start <= end) {
            int middle = start + (end - start) / 2;
            if (target == arr[middle]) {
                return middle;
            } else if (target < arr[middle]) {
                end = middle - 1;
            } else if (target > arr[middle]) {
                start = middle + 1;
            }
        }
        // In case value not found
        return -1;
    }
}

Interpolation search algorithm , is very much similar to binary search algoirhtm , because for the implementation of interpolation search , just like binary search the array must be sorted in either ascending or descending order but at the same time one additional condition which must be satisfied to implement interpolation search is that the difference between the values in the array must be linear.

In case of interpolation search the only thing which differentiates it from binary search is the way searching happens in interpolation search . Basically in case of binary search algorithm we directly went to the middle value present in the array irrespective the target value , but in interpolation search we go to different locations according to search key.

animation-541x141.gif

In the interpolation gif , you can easily see that instead for simply going to the middle value we are going to some specific value by taking target valeu into consideration.

Now the question which must be there in your mind would be , how we figure out which location to move to with every iteration , so the answer to this query is that we use a mathematical formula which helps us the find the location to move on taking target value in consideration.

1.png

import java.util.*;

public class interpolationSearch {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int[] arr = { 1, 2, 4, 6, 8, 10, 12, 15 };
        int target;
        System.out.print("Enter the target value : ");
        target = sc.nextInt();

        // Call the function to find the value
        int ans = find(arr, target);
        if (ans == -1) {
            System.out.println("Value not found !!");
        } else {
            System.out.println("Value found at : " + ans);
        }
    }

    static int find(int[] arr, int target) {
        // First let us define the search space
        int start = 0;
        int end = arr.length - 1;
        while (start <= end) {
            int pos = end + (start - end) * ((target - arr[end]) / (arr[start] - arr[end]));

            if (target < arr[pos]) {
                end = pos - 1;
            } else if (target > arr[pos]) {
                start = pos + 1;
            } else if (target == arr[pos]) {
                return pos;
            }
        }

        // If value not found
        return -1;
    }

}

Space and Time complexity Analysis

Time complextiy (4).png

By seeing the average case time complextiy you can understand that interpolation search is even faster than the binary search algorithm , but in order to better understand how much fast is interpolation search than binary search in average case scenario , let us take an example :

Given an input size of 256.

log(n) will have 8 iterations that is 2^8 , but in case of interpolation search log(log(n)) will have 3 iterations .

image.png

Did you find this article valuable?

Support Yuvraj Singh by becoming a sponsor. Any amount is appreciated!