What is the difference between Linear and Binary Search?

Linear Search:

A linear search is also known as a sequential search that simply scans each element at a time. Suppose we want to search for an element in an array or list; we simply calculate its length and do not jump at any item.

Below is the code syntax for the linear search.

// Linear Search in C++
 
#include <iostream>
using namespace std;
 
int search(int array[], int n, int x)
{
 
    // Going through array sequencially
    for (int i = 0; i < n; i++)
        if (array[i] == x)
            return i;
    return -1;
}

Binary Search:

A binary search is a search in which the middle element is calculated to check whether it is smaller or larger than the element which is to be searched. The main advantage of using binary search is that it does not scan each element in the list. Instead of scanning each element, it performs the searching to the half of the list. So, the binary search takes less time to search an element as compared to a linear search.

Below is the code syntax for the binary search.


#include <iostream>
using namespace std;
 
int binarySearch(int array[], int x, int low, int high)
{
 
    // Repeat until the pointers low and high meet each
    // other
    while (low <= high) {
        int mid = low + (high - low) / 2;
 
        if (array[mid] == x)
            return mid;
 
        if (array[mid] < x)
            low = mid + 1;
 
        else
            high = mid - 1;
    }
 
    return -1;
}