Open In App

Linear Search vs Binary Search

Last Updated : 19 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report
 

Prerequisite:

LINEAR SEARCH

Assume that item is in an array in random order and we have to find an item. Then the only way to search for a target item is, to begin with, the first position and compare it to the target. If the item is at the same, we will return the position of the current item. Otherwise, we will move to the next position. If we arrive at the last position of an array and still can not find the target, we return -1. This is called the Linear search or Sequential search.

 

Below is the code syntax for the linear search.

C++




// 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;
}


C




// Linear Search in C
 
#include <stdio.h>
 
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;
}


Java




/*package whatever //do not write package name here */
 
import java.io.*;
 
class Main {
    public static int liner(int arr[], int x)
    {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == x)
                return i;
        }
        return -1;
    }
}


Python




# Linear Search in Python
 
 
def linearSearch(array, n, x):
 
    for i in range(0, n):
        if (array[i] == x):
            return i
    return -1


C#




// Linear Search in c#
using System;
using System.Collections.Generic;
  
class GFG
{
  public static 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;
  }
}
  
// This code is contributed by adityapatil12.


Javascript




<script>
 
// Linear Search in C++
 
function search(array, n, x)
{
 
    // Going through array sequencially
    for (let i = 0; i < n; i++){
        if (array[i] == x){
            return i;
        }      
    }     
    return -1;
}
 
// The coee is contributed by Gautam goel.
</script>


BINARY SEARCH

In a binary search, however, cut down your search to half as soon as you find the middle of a sorted list. The middle element is looked at to check if it is greater than or less than the value to be searched. Accordingly, a search is done to either half of the given list

 

Below is the code syntax for the binary search.

C++




#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;
}


C




#include <stdio.h>
 
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;
}


Java




/*package whatever //do not write package name here */
 
class GFG {
    public static int binary(int[] arr, int x)
    {
        int start = 0;
        int end = arr.length - 1;
        while (start <= end) {
            int mid = (start + end) / 2;
            if (x == arr[mid]) {
                return mid;
            }
            else if (x > arr[mid]) {
                start = mid + 1;
            }
            else {
                end = mid - 1;
            }
        }
        return -1;
    }
}


Python




def binarySearch(array, x, low, high):
 
    # Repeat until the pointers low and high meet each other
    while low <= high:
 
        mid = low + (high - low)//2
 
        if array[mid] == x:
            return mid
 
        elif array[mid] < x:
            low = mid + 1
 
        else:
            high = mid - 1
 
    return -1


C#




// Linear Search in c#
using System;
using System.Collections.Generic;
  
class GFG
{
  public static int binary(int[] arr, int x)
  {
    int start = 0;
    int end = arr.Length - 1;
    while (start <= end) {
        int mid = (start + end) / 2;
        if (x == arr[mid]) {
            return mid;
        }
        else if (x > arr[mid]) {
            start = mid + 1;
        }
        else {
            end = mid - 1;
        }
    }
    return -1;
  }
}
  
// This code is contributed by aditya942003patil


Javascript




<script>
 
function binarySearch(array, x, low, 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;
}
 
// The code is contributed by gautam goel.
 
</script>


Important Differences 

Linear Search 

Binary Search

In linear search input data need not to be in sorted. In binary search input data need to be in sorted order.
It is also called sequential search. It is also called half-interval search.
The time complexity of linear search O(n).  The time complexity of binary search O(log n).
Multidimensional array can be used. Only single dimensional array is used.
Linear search performs equality comparisons Binary search performs ordering comparisons
It is less complex. It is more complex.
It is very slow process. It is very fast process.

Let us look at an example to compare the two:

Linear Search to find the element “J” in a given sorted list from A-X

linear-search

Binary Search to find the element “J” in a given sorted list from A-X

binary-search  

LINEAR SEARCHING EXAMPLE:

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;
}
 
int main()
{
    int array[] = { 12, 114, 0, 4, 9 };
    int x = 4;
    int n = sizeof(array) / sizeof(array[0]);
 
    int result = search(array, n, x);
 
    (result == -1)
        ? cout << "Element not found"
        : cout << "Element found at index: " << result;
}


C




#include <stdio.h>
 
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;
}
 
int main()
{
    int array[] = { 12, 114, 0, 4, 9 };
    int x = 4;
    int n = sizeof(array) / sizeof(array[0]);
 
    int result = search(array, n, x);
 
    (result == -1)
        ? printf("Element not found")
        : printf("Element found at index: %d", result);
}


Java




/*package whatever //do not write package name here */
import java.io.*;
 
class GFG {
    public static int liner(int arr[], int x)
    {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == x)
                return i;
        }
        return -1;
    }
    public static void main(String[] args)
    {
          int arr[] = { 12, 114, 0, 4, 9 };
   
        int search = liner(
            arr,
            4); // Here we are searching for 10 element in
                 // the array which is not present in the
                 // array so, it will print -1
        System.out.println(search);
    }
}


Python




def linearSearch(array, n, x):
 
    for i in range(0, n):
        if (array[i] == x):
            return i
    return -1
 
 
array = [24, 41, 31, 11, 9]
x = 11
n = len(array)
result = linearSearch(array, n, x)
if(result == -1):
    print("Element not found")
else:
    print("Element is Present at Index: ", result)


C#




// C# program to implement above approach
using System;
using System.Collections.Generic;
  
class GFG
{
  public static int liner(int[] arr, int x)
  {
    for (int i = 0; i < arr.Length; i++) {
        if (arr[i] == x)
            return i;
    }
    return -1;
  }
  
  // Driver Code
  public static void Main(string[] args){
   
    int[] arr = { 12, 114, 0, 4, 9 };
    int search = liner(arr, 4); // Here we are searching for 10 element in
                                 // the array which is not present in the
                                 // array so, it will print -1
    Console.Write(search);
  }
}
//this code is contributed by aditya942003patil


Javascript




function search(array, n, x)
{
 
    // Going through array sequencially
    for (let i = 0; i < n; i++)
        if (array[i] == x)
            return i;
    return -1;
}
 
 
array = [12, 114, 0, 4, 9 ];
x = 4;
n = array.length;
result = search(array, n, x);
 
 
if(result == -1){
    console.log("Element not found");
}
else{
    console.log("Elementn found at index: ", result);
}
 
// The code is contributed by Nidhi goel


Output

Element found at index: 3


Time Complexity: O(n), where n is the size of the input array. The worst-case scenario is when the target element is not present in the array, and the function has to go through the entire array to figure that out.
Auxiliary Space: O(1), the function uses only a constant amount of extra space to store variables. The amount of extra space used does not depend on the size of the input array.

BINARY SEARCHING EXAMPLE:

C++




#include<bits/stdc++.h>
using namespace std;
 
int binarySearch(vector<int> arr,int x,int low,int high){
 
    while(low <= high){
 
        int mid = low + (high - low)/2;
 
        if (arr[mid] == x)
            return mid;
 
        else if (arr[mid] < x)
            low = mid + 1;
        else
            high = mid - 1;
    }
 
    return -1;
}
 
int main(){
    vector<int> arr = {2, 4, 5, 7, 14, 17, 19, 22};
    int x = 22;
 
    int result = binarySearch(arr, x, 0, arr.size()-1);
 
    if (result != -1)
        cout << result << endl;
    else
        cout << "Not found" << endl;
    return 0;
}
 
 
// The code is constributed by Nidhi goel


C




#include <stdio.h>
 
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;
}
 
int main( )
{
    int array[] = { 2, 4, 5, 7, 14, 17, 19, 22 };
    int n = sizeof(array) / sizeof(array[0]);
    int x = 22;
    int result = binarySearch(array, x, 0, n - 1);
    if (result == -1)
        printf("Not found");
    else
        printf(" %d", result);
    return 0;
}


Java




/*package whatever //do not write package name here */
 
public class GFG {
    public static int binary(int arr[], int x)
    {
        int start = 0;
        int end = arr.length - 1;
        while (start <= end) {
            int mid = (start + end) / 2;
            if (x == arr[mid]) {
                return mid;
            }
            else if (x > arr[mid]) {
                start = mid + 1;
            }
            else {
                end = mid - 1;
            }
        }
        return -1;
    }
    public static void main(String[] args)
    {
        int arr[] = { 2, 4, 5, 7, 14, 17, 19, 22};
        int search = binary(arr, 22);
        System.out.println(search);
    }
}


Python




def binarySearch(array, x, low, high):
 
    while low <= high:
 
        mid = low + (high - low)//2
 
        if array[mid] == x:
            return mid
 
        elif array[mid] < x:
            low = mid + 1
 
        else:
            high = mid - 1
 
    return -1
 
 
array = [2, 4, 5, 7, 14, 17, 19, 22]
x = 22
 
result = binarySearch(array, x, 0, len(array)-1)
 
if result != -1:
    print(str(result))
else:
    print("Not found")


C#




using System;
using System.Collections.Generic;
  
class GFG
{
  public static int binary(int[] arr, int x)
  {
    int start = 0;
    int end = arr.Length - 1;
    while (start <= end) {
        int mid = (start + end) / 2;
        if (x == arr[mid]) {
            return mid;
        }
        else if (x > arr[mid]) {
            start = mid + 1;
        }
        else {
            end = mid - 1;
        }
    }
    return -1;
  }
  
  // Driver Code
  public static void Main(string[] args){
  
    int[] arr = { 2, 4, 5, 7, 14, 17, 19, 22 };
    int search = binary(arr, 22);
    Console.Write(search);
  }
}
// This code is contributed by aditya942003patil


Javascript




<script>
 
function binarySearch(array, x, low, high){
 
    while(low <= high){
 
        let mid = low + Math.floor((high - low)/2);
 
        if (array[mid] == x)
            return mid;
 
        else if (array[mid] < x)
            low = mid + 1;
        else
            high = mid - 1;
    }
 
    return -1;
}
 
let array = [2, 4, 5, 7, 14, 17, 19, 22];
let x = 22;
 
let result = binarySearch(array, x, 0, array.length-1);
if (result != -1)
    console.log(result);
else
    console.log("Not found");
 
// The code is constributed by Nidhi goel
</script>


Output

 7


Time Complexity: O(log n) – Binary search algorithm divides the input array in half at every step, reducing the search space by half, and hence has a time complexity of logarithmic order.
Auxiliary Space: O(1) – Binary search algorithm requires only constant space for storing the low, high, and mid indices, and does not require any additional data structures, so its auxiliary space complexity is O(1).



Previous Article
Next Article

Similar Reads

Is Sentinel Linear Search better than normal Linear Search?
What is Sentinel Linear Search? Sentinel Linear search is a type of linear search where the element to be searched is placed in the last position and then all the indices are checked for the presence of the element without checking for the index out of bound case. The number of comparisons is reduced in this search as compared to a traditional line
9 min read
Which is faster between binary search and linear search?
In computer science, search algorithms are used to locate a specific element within a data structure. Two commonly used search algorithms are binary search and linear search. Understanding their relative speeds is crucial for optimizing search operations. Let's compare the speed of Binary Search and Linear Search to determine which one is faster. B
2 min read
Difference Between Linear Search and Jump Search
Linear Search and Jump Search are two different techniques used to find an element in a list. Each algorithm has its own set of characteristics, advantages, and limitations, making them suitable for different scenarios. This article explores the key differences between Linear Search and Jump Search. What is Linear Search?Linear Search, also known a
3 min read
Difference between Linear and Non-linear Data Structures
Linear Data Structure: Data structure where data elements are arranged sequentially or linearly where each and every element is attached to its previous and next adjacent is called a linear data structure. In linear data structure, single level is involved. Therefore, we can traverse all the elements in single run only. Linear data structures are e
5 min read
Meta Binary Search | One-Sided Binary Search
Meta binary search (also called one-sided binary search by Steven Skiena in The Algorithm Design Manual on page 134) is a modified form of binary search that incrementally constructs the index of the target value in the array. Like normal binary search, meta binary search takes O(log n) time. Meta Binary Search, also known as One-Sided Binary Searc
9 min read
Recursive Linear Search Algorithm
Linear Search is defined as a sequential search algorithm that starts at one end and goes through each element of a list until the desired element is found, otherwise the search continues till the end of the data set. How Linear Search Works? Linear search works by comparing each element of the data structure with the key to be found. To learn the
6 min read
Linear search using Multi-threading
Given a large file of integers, search for a particular element in it using multi-threading. Examples: Input : 1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220Output :if key = 20Key element foundInput :1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220Output :if key = 202Key not presentPrerequisite : Multi-threading Recommen
6 min read
Number of comparisons in each direction for m queries in linear search
Given an array containing N distinct elements. There are M queries, each containing an integer X and asking for the index of X in the array. For each query, the task is to perform linear search X from left to right and count the number of comparisons it took to find X and do the same thing right to left. In the end, print the total number of compar
7 min read
Sentinel Linear Search
Sentinel Linear Search as the name suggests is a type of Linear Search where the number of comparisons is reduced as compared to a traditional linear search. In a traditional linear search, only N comparisons are made, and in a Sentinel Linear Search, the sentinel value is used to avoid any out-of-bounds comparisons, but there is no additional comp
12 min read
Linear Search Visualization using JavaScript
GUI(Graphical User Interface) helps in better in understanding than programs. In this article, we will visualize Linear Search using JavaScript. We will see how the elements are being traversed in Linear Search until the given element is found. We will also visualize the time complexity of Linear Search. Reference: Linear SearchAsynchronous Functio
3 min read
Article Tags :
Practice Tags :