Difference Between Linear Search and Binary Search



A linear search compares the target element with each array element, while a binary search uses divide-and-conquer method to efficiently search for the target element. In this article, we will compare linear search and binary search.

What is Linear Search?

Linear search is a sequential searching algorithm where we traverse every element within the input array and compare it with the target element to be found. If the target element is found, we return true and the index, and return false if the element is not found in the given array.

Below is an animation of working of linear search to find the element 42:

Linear Search Animation

Example

Here is an example of implementing linear search in C, C++, Java, Python, and Javascript:

#include <stdio.h>
void linear_search(int a[], int n, int key){
   int i, count = 0;
   for(i = 0; i < n; i++) {
      if(a[i] == key) { // compares each element of the array
         printf("The element %d is found at %d position
", key, i+1); count = count + 1; } } if(count == 0) // for unsuccessful search printf("The element %d is not present in the array
", key); } int main(){ int i, n, key; int a[10] = {12, 44, 32, 18, 4, 10}; n = sizeof(a) / sizeof(a[0]); printf("Array elements: "); for(i=0; i<n; i++) { printf("%d ", a[i]); } printf("\n"); key = 18; linear_search(a, n, key); key = 23; linear_search(a, n, key); return 0; }

Output

Array elements: 12 44 32 18 4 10 
The element 18 is found at 4 position
The element 23 is not present in the array
#include <iostream>
using namespace std;
void linear_search(int a[], int n, int key){
   int i, count = 0;
   for(i = 0; i < n; i++) {
     if(a[i] == key) { // compares each element of the array
       cout << "The element " << key << " is found at position " << i+1 << endl;
       count = count + 1;
     }
   }
   if(count == 0) // for unsuccessful search
     cout << "The element " << key << " is not present in the array" << endl;
}
int main(){
   int i, n, key;
   int a[10] = {12, 44, 32, 18, 4, 10};
   n = sizeof(a) / sizeof(a[0]);
   cout << "Array elements: ";
   for(i=0; i<n; i++) {
      cout << a[i] << " ";
   }
   cout << endl;
   key = 18;
   linear_search(a, n, key);
   key = 23;
   linear_search(a, n, key);
   return 0;
}

Output

Array elements: 12 44 32 18 4 10 
The element 18 is found at position 4
The element 23 is not present in the array
import java.io.*;
import java.util.*;
public class LinearSearch {
   static void linear_search(int a[], int n, int key) {
      int i, count = 0;
      for(i = 0; i < n; i++) {
         if(a[i] == key) { // compares each element of the array
            System.out.println("The element " + key + " is found at position " + (i+1));
            count = count + 1;
         }
      }
      if(count == 0) // for unsuccessful search
         System.out.println("The element " + key + " is not present in the array");
      }
   public static void main(String args[]) {
      int i, n, key;
      int a[] = {12, 44, 32, 18, 4, 10, 66};
      n = a.length;
      System.out.print("Array elements: ");
      for(i=0; i<n; i++) {
         System.out.print(a[i] + " ");
      }
      System.out.println();
      key = 10;
      linear_search(a, n, key);
      key = 54;
      linear_search(a, n, key);
   }
}

Output

Array elements: 12 44 32 18 4 10 66 
The element 10 is found at position 6
The element 54 is not present in the array
def linear_search(a, n, key):
   count = 0
   for i in range(n):
      if(a[i] == key):
         print("The element", key, "is found at position", (i+1))
         count = count + 1
   if(count == 0):
      print("The element", key, "is not present in the array")

a = [14, 56, 77, 32, 84, 9, 10]
n = len(a)
print("Array elements:", *a)
key = 32
linear_search(a, n, key)
key = 3
linear_search(a, n, key)

Output

Array elements: 14 56 77 32 84 9 10
The element 32 is found at position 4
The element 3 is not present in the array
let nums = [10, 25, 30, 45, 50];
let target = 45;

console.log("Array:", nums);
let result = linearSearch(nums, target);

function linearSearch(arr, target) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === target) {
            return i;
        }
    }
    return -1;
}

if (result !== -1) {
    console.log(`The element ${target} is found at position ${result + 1}`);
} else {
    console.log(`The element ${target} is not present in the array`);
}

Output

Array: [ 10, 25, 30, 45, 50 ]
The element 45 is found at position 4

What is Binary Search?

The binary search algorithm works as per the divide-and-conquer principle, as it keeps dividing the array in half before searching. To search for an element in an array using binary search, the array should be sorted.

In the sorted array, we find the middle element and compare it with the element that has to be searched, and based on the comparison, we either search in the left or right sub-array or return the middle element.

Below is an animation of working of binary search in a sorted array to find the element 42:

Binary Search Animation

Example

Here is an example of implementing binary search in C, C++, Java, Python, and Javascript.

#include<stdio.h>
void binary_search(int a[], int low, int high, int key){
   int mid;
   mid = (low + high) / 2;
   if (low <= high) {
      if (a[mid] == key)
         printf("The element %d is found at index: %d
", key, mid); else if(key < a[mid]) binary_search(a, low, mid-1, key); else if (a[mid] < key) binary_search(a, mid+1, high, key); } else if (low > high) printf("The element %d is not present in the array
", key); } int main(){ int a[] = {12, 14, 18, 22, 39}; int n = sizeof(a) / sizeof(a[0]); int low = 0, high = n-1; printf("Array: "); for(int i=0; i<n; i++) printf("%d ", a[i]); printf("\n"); int key = 22; binary_search(a, low, high, key); key = 23; binary_search(a, low, high, key); return 0; }

Output

Array: 12 14 18 22 39 
The element 22 is found at index: 3
The element 23 is not present in the array
#include <iostream>
using namespace std;
void binary_search(int a[], int low, int high, int key){
   int mid;
   mid = (low + high) / 2;
   if (low <= high) {
      if (a[mid] == key)
         cout << "The element " << key << " is found at index: " << mid << endl;
      else if(key < a[mid])
         binary_search(a, low, mid-1, key);
      else if (a[mid] < key)
         binary_search(a, mid+1, high, key);
   } else if (low > high)
      cout << "The element " << key << " is not present in the array" << endl;
}
int main(){
   int a[] = {12, 14, 18, 22, 39};
   int n = sizeof(a) / sizeof(a[0]);   
   int low = 0, high = n-1;

   cout << "Array: ";
   for(int i=0; i<n; i++) cout << a[i] << " ";
   cout << endl;

   int key = 22;
   binary_search(a, low, high, key);
   key = 23;
   binary_search(a, low, high, key);
   return 0;
}

Output

Array: 12 14 18 22 39 
The element 22 is found at index: 3
The element 23 is not present in the array
import java.util.*;
public class BinarySearch {
   static void binary_search(int a[], int low, int high, int key) {
      int mid = (low + high) / 2;
      if (low <= high) {
         if (a[mid] == key)
            System.out.println("The element " + key + " is found at index: " + mid);
         else if(key < a[mid])
            binary_search(a, low, mid-1, key);
         else if (a[mid] < key)
            binary_search(a, mid+1, high, key);
      } else if (low > high)
         System.out.println("The element " + key + " is not present in the array");
   }
   public static void main(String args[]) {
      int a[] = {12, 14, 18, 22, 39};
      int n = a.length;   
      int low = 0, high = n-1;

      System.out.print("Array: ");
      for(int i=0; i<n; i++) System.out.print(a[i] + " ");
      System.out.println();

      int key = 22;
      binary_search(a, low, high, key);
      key = 23;
      binary_search(a, low, high, key);
   }
}

Output

Array: 12 14 18 22 39 
The element 22 is found at index: 3
The element 23 is not present in the array
def binary_search(a, low, high, key):
   mid = (low + high) // 2
   if (low <= high):
      if(a[mid] == key):
         print("The element", key, "is found at index:", mid)
      elif(key < a[mid]):
         binary_search(a, low, mid-1, key)
      elif (a[mid] < key):
         binary_search(a, mid+1, high, key)
   if(low > high):
      print("The element", key, "is not present in the array")

a = [6, 12, 14, 18, 22, 39, 55, 182]
n = len(a)   
print("Array:", a)

low = 0
high = n-1
key = 22
binary_search(a, low, high, key)
key = 54
binary_search(a, low, high, key)

Output

Array: [6, 12, 14, 18, 22, 39, 55, 182]
The element 22 is found at index: 4
The element 54 is not present in the array
let nums = [10, 20, 30, 40, 50, 60, 70];
let target = 40;

console.log("Array:", nums);   
let result = binarySearch(nums, target);

function binarySearch(arr, target) {
    let left = 0;
    let right = arr.length - 1;   

    while (left <= right) {
        let mid = Math.floor((left + right) / 2);

        if (arr[mid] === target) {
            return mid;
        } else if (arr[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return -1;
}

if (result !== -1) {
    console.log(`The element ${target} is found at index: ${result}`);
} else {
    console.log(`The element ${target} is not present in the array`);
}

Output

Array: [ 10, 20, 30, 40, 50, 60, 70 ]
The element 40 is found at index: 3

Difference Between Linear Search and Binary Search

The key differences between linear and binary search are as follows:

Binary Search Linear Search
The data element must be sorted. The data elements may not be sorted.
Time complexity: O(log n) Time complexity: O(n)
It works on 1-D array. It works on single as well as multi-dimensional arrays.
It is more complex and faster algorithm compared to linear search. It is a simple but slow algorithm.
This is used for comparing a large number of datasets. This is useful for smaller dataset.
It uses divide and conquer approach. It uses brute force approach.
Space complexity: O(1) using iteration and O(log n) using recursion. Space complexity: O(1)

Linear Search vs Binary Search: When to use?

The linear search is used on small, unsorted dataset as it compares the target element with each array element one by one. The binary search is used on larger and sorted dataset as it works on divide and conquer principle. It keeps dividing the dataset around middle element and discards the sub-part that will not be used for comparison. The time complexity of linear search, O(n), is reduced to O(log n) in binary search.

Updated on: 2025-08-21T19:18:50+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements