Searching Algorithms
Tags: dsawithkunal, python, java, algorithms
Published: 2021-09-10 13:45:26

<p><strong>Searching algorithms</strong>&nbsp;is a basic, fundamental step in computing done via a step-by-step method to locate specific data among a collection of data.<br />
&nbsp;</p>

<h1><strong>What is a Search Algorithm?</strong></h1>

<p>According to Wikipedia- Search algorithm is-</p>

<p><em>Any algorithm which solves the search problem, namely, to retrieve information stored within some data structure, or calculated in the search space of a problem domain, either with discrete or continuous values.</em></p>

<p>They&nbsp;are designed to check or retrieve an element from any&nbsp;data structure&nbsp;where it is being stored. They search for a target (key) in the search space.<br />
&nbsp;</p>

<h1><strong>Types of Searching Algorithms</strong></h1>

<p>In this post, we are basically&nbsp;going to discuss two important algorithms -</p>

<ol>
	<li><strong>Linear or Sequential Search</strong></li>
	<li><strong>Binary Search</strong></li>
</ol>

<p>Let us discuss these two in detail with examples, code implementation, and time complexity analysis.<br />
&nbsp;</p>

<h1><strong>Linear or Sequential Search</strong></h1>

<p>This algorithm works by sequentially iterating through the whole array or list from one end until the target element is found. If the element is found, it returns its index, else -1.</p>

<p>Now let us take an example and try to understand :</p>

<pre>
<code>arr = [2, 12, 15, 11, 7, 19, 45]</code></pre>

<p>Suppose, the target element to be searched is&nbsp; <code>7</code>.</p>

<h3><strong><u>Approach </u>:</strong></h3>

<ul>
	<li>Start with index 0 and compare each element with the target</li>
	<li>If the target is found to be equal to the element, return its index</li>
	<li>If the target is not found, return -1</li>
</ul>

<h3><u><strong>Code Implementation</strong></u></h3>

<p><strong>In Java</strong></p>

<pre>
<code>package algorithms.searching;

public class LinearSearch {
    public static void main(String[] args) {
        int[] nums = {2, 12, 15, 11, 7, 19, 45};
        int target = 7;
        System.out.println(search(nums, target));

    }

    static int search(int[] nums, int target) {
        for (int index = 0; index &lt; nums.length; index++) {
            if (nums[index] == target) {
                return index;
            }
        }
        return -1;
    }
}
</code></pre>

<p>&nbsp;</p>

<p><strong>In Python</strong></p>

<pre>
<code>def search(nums, target):
    for i in range(len(nums)):
        if nums[i] == target:
            return i
    return -1

if __name__ == &#39;__main__&#39;:
    nums = [2, 12, 15, 11, 7, 19, 45]
    target = 7
    print(search(nums, target))</code></pre>

<p>&nbsp;</p>

<h3><u><strong>Time Complexity Analysis</strong></u></h3>

<ul>
	<li><strong>Best Case:&nbsp;</strong>The best case occurs when the target element is the first element of the array. The number of comparisons, in this case, is 1. So, the time complexity is <code>O(1)</code>.</li>
	<li><strong>Average Case:&nbsp;</strong>On average, the target element will be somewhere in the middle of the array. The number of comparisons, in this case, will be N/2. So, the time complexity will be <code>O(N)</code> (the constant being ignored).</li>
	<li><strong>Worst Case:</strong> The worst case occurs when the target element is the last element in the array or not in the array. In this case, we have to traverse the entire array, and hence the number of comparisons will be N. So, the time complexity will be <code>O(N)</code>.</li>
</ul>

<p>&nbsp;</p>

<h1><strong>Binary Search</strong></h1>

<p>This type of&nbsp;searching algorithm&nbsp;is used to find the position of a specific value contained <strong>in a sorted array</strong>. The binary search algorithm works on the principle of divide &amp; conquer and it is considered the best searching algorithm because of its faster speed to search.&nbsp;</p>

<p>Now let us take a sorted array as an example and try to understand :</p>

<pre>
<code>arr = [2, 12, 15, 17, 27, 29, 45]</code></pre>

<p>Suppose, the target element to be searched is&nbsp; 1<code>7</code>.</p>

<h3><u><strong>Approach</strong></u></h3>

<ul>
	<li>Compare&nbsp;the target element with the middle element of the array.</li>
	<li>If the target element is greater than the middle element, then&nbsp;the search continues in the right half.</li>
	<li>Else if the target element is less than the middle value, the search continues in the left half.</li>
	<li>This process is repeated until the middle element is equal to the target&nbsp;element, or the target element is not in the array</li>
	<li>If the target element is found, its index is returned, else -1 is returned.</li>
</ul>

<h3><strong>&nbsp;<u>Code Implementation</u></strong></h3>

<p><strong>In Java</strong></p>

<pre>
<code>package algorithms.searching;

public class BinarySearch {
    public static void main(String[] args) {
        int[] nums = {2, 12, 15, 17, 27, 29, 45};
        int target = 17;
        System.out.println(search(nums, target));
    }

    static int search(int[] nums, int target) {
        int start = 0;
        int end = nums.length - 1;

        while (start &lt;= end) {
            int mid = start + (end - start) / 2;

            if (nums[mid] &gt; target)
                end = mid - 1;
            else if (nums[mid] &lt; target)
                start = mid + 1;
            else
                return mid;
        }
        return -1;
    }
}
</code></pre>

<p>&nbsp;</p>

<p><strong>In Python</strong></p>

<pre>
<code>def search(nums, target):
    start = 0
    end = len(nums)-1

    while start &lt;= end:
        mid = start + (end-start)//2


        if nums[mid] &gt; target:
            end = mid-1
        elif nums[mid] &lt; target:
            start = mid+1
        else:
            return mid

    return -1


if __name__ == &#39;__main__&#39;:
    nums = [2, 12, 15, 17, 27, 29, 45]
    target = 17
    print(search(nums, target))</code></pre>

<p>&nbsp;</p>

<h3><u><strong>Time Complexity Analysis</strong></u></h3>

<ul>
	<li><strong>Best Case:&nbsp;</strong>The best case occurs when the target element is the middle element of the array. The number of comparisons, in this case, is 1. So, the time complexity is <code>O(1)</code>.</li>
	<li><strong>Average Case:</strong>&nbsp;On average, the target element will be somewhere in the array. So, the time complexity will be <code>O(logN)</code></li>
	<li><strong>Worst Case:&nbsp;</strong>The worst case occurs when the target element is not in the list or it is away from the middle element. So, the time complexity will be <code>O(logN)</code></li>
</ul>

<p><strong>Calculating Time complexity:</strong></p>

<ul>
	<li>Let say the iteration in Binary Search terminates after&nbsp;<strong>k</strong>&nbsp;iterations.</li>
	<li>At each iteration, the array is divided by half. So let&rsquo;s say the length of array at any iteration is&nbsp;<strong>N</strong></li>
	<li>At&nbsp;<strong>Iteration 1,</strong>
	<pre>
<code>Length of array = N</code></pre>
	</li>
	<li>At&nbsp;<strong>Iteration 2</strong>,
	<pre>
<code>Length of array = N/2</code></pre>
	</li>
	<li>At <strong>Iteration 3</strong>,
	<pre>
<code>Length of array = (N/2)/2 = N/2^2</code></pre>
	</li>
	<li>At <strong>Iteration k</strong>,
	<pre>
<code>Length of array = N/2^k</code></pre>
	</li>
	<li>Also, we know that after k divisions, the <strong>length of array becomes 1</strong>
	<pre>
Length of array = <strong>N&frasl;2k = 1</strong>
=&gt; <strong>N = 2k</strong></pre>
	</li>
	<li>Applying log function on both sides:
	<pre>
=&gt; <strong>log2 (N) = log2 (2k)</strong>
=&gt; <strong>log2 (N) = k log2 (2)</strong></pre>
	</li>
	<li>As&nbsp;<strong>(loga&nbsp;(a) = 1)</strong><br />
	Therefore,
	<pre>
=&gt; <strong>k = log2 (N)</strong></pre>
	</li>
	<li>
	<p><strong>Hence, the time complexity of Binary Search is log2&nbsp;(N)</strong><br />
	&nbsp;</p>
	</li>
</ul>

<p>&nbsp;You can also visualise the above two algorithms using the simple tool built by <a href="https://www.linkedin.com/in/dipesh-patil/">Dipesh Patil</a>&nbsp;-&nbsp;<a href="https://dipeshpatil.github.io/algorithms-visualiser/#/searching">Algorithms Visualiser</a><br />
&nbsp;</p>

<h1><strong>Order-agnostic Binary Search</strong></h1>

<p>Suppose, we have to find a target element in a sorted array.&nbsp;Though we know that the array is sorted, we don&rsquo;t know if it&rsquo;s sorted in ascending or descending order.</p>

<h3><br />
<u><strong>Approach</strong></u></h3>

<p>The implementation is similar to&nbsp;binary search&nbsp;except that we need to identify whether the array is sorted in ascending order or descending order to make the decision about whether to continue the search in the left half of the array or the right half of the array.</p>

<ul>
	<li>We first compare the target with the middle element</li>
	<li>If&nbsp;<em>the array is sorted in ascending order and the target&nbsp;is less than the middle element</em>&nbsp;<strong>OR</strong>&nbsp;<em>the array is sorted in descending order and the target&nbsp;is greater than the middle element</em>&nbsp;then we continue the search in the lower half of the array by setting&nbsp;<code>end=mid-1</code>.</li>
	<li>Otherwise, we perform the search in the upper half of the array by setting&nbsp;<code>start=mid+1</code></li>
</ul>

<p>The only thing we need to do is to figure out whether the array is sorted in ascending order or descending order. We can easily find this by comparing the first and last elements of the array.</p>

<pre>
<code>if arr[0] &lt; arr[arr.length-1]
    array is sorted in ascending order 
else
    array is sorted in descending order</code></pre>

<h3><br />
<u><strong>Code Implementation</strong></u></h3>

<p><strong>&nbsp;In Java</strong></p>

<pre>
<code>package algorithms.searching;

public class OrderAgnosticBinarySearch {
    public static void main(String[] args) {
        int[] nums1 = {-1, 2, 4, 6, 7, 8, 12, 15, 19, 32, 45, 67, 99};
        int[] nums2 = {99, 67, 45, 32, 19, 15, 12, 8, 7, 6, 4, 2, -1};
        int target = -1;
        System.out.println(search(nums1, target));
        System.out.println(search(nums2, target));
    }

    static int search(int[] arr, int target) {
        int start = 0;
        int end = arr.length - 1;

        boolean isAscending = arr[start] &lt; arr[end];

        while (start &lt;= end) {
            int mid = start + (end - start) / 2;

            if (target == arr[mid])
                return mid;

            if (isAscending) {
                if (target &lt; arr[mid]) {
                    end = mid - 1;
                } else {
                    start = mid + 1;
                }
            } else {
                if (target &lt; arr[mid]) {
                    start = mid + 1;
                } else {
                    end = mid - 1;
                }
            }
        }
        return -1;
    }


}
</code></pre>

<p>&nbsp;</p>

<p><strong>In Python</strong></p>

<pre>
<code>def search(nums, target):
    start = 0
    end = len(nums)-1

    is_ascending = nums[start] &lt; nums[end]

    while start &lt;= end:
        mid = start + (end-start)//2

        if target == nums[mid]:
            return mid

        if is_ascending:
            if target &lt; nums[mid]:
                end = mid-1
            else:
                start = mid+1
        else:
            if target &lt; nums[mid]:
                start = mid+1
            else:
                end = mid-1

    return -1


if __name__ == &#39;__main__&#39;:
    nums1 = [-1, 2, 4, 6, 7, 8, 12, 15, 19, 32, 45, 67, 99]
    nums2 = [99, 67, 45, 32, 19, 15, 12, 8, 7, 6, 4, 2, -1]
    target = -1
    print(search(nums1, target))
    print(search(nums2, target))
</code></pre>

<p>&nbsp;</p>

<h3><u><strong>Time Complexity Analysis</strong></u></h3>

<p>There will be no change in the time complexity and hence will be the same as Binary Search.</p>

<p>&nbsp;</p>

<h1><strong>Conclusion</strong></h1>

<p>In this blog, we discussed the two most important searching algorithms. This blog post cannot end without thanking the person who has motivated a lot of students to learn DSA, that too free of cost - <strong><a href="https://www.linkedin.com/in/kunal-kushwaha/">Kunal Kushwaha</a></strong>&nbsp;and <a href="https://www.linkedin.com/company/commclassroom/"><strong>Community Classroom</strong></a>. You can also access his free DSA playlist <a href="https://www.youtube.com/playlist?list=PL9gnSGHSqcnr_DxHsP7AW9ftq0AtAyYqJ">here</a>.<br />
I will also soon be publishing it on <a href="https://www.geeksforgeeks.org/">GeeksforGeeks</a>.</p>