Skip to content
Related Articles

Related Articles

Linear Search vs Binary Search

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 04 Aug, 2022
 

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.

 

Complete Interview Preparation - GFG

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.

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

 

Complete Interview Preparation - GFG

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

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 comparisonsBinary 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  

LINER 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 GFG()
{
    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 GFG()
{
    int array[] = { 24, 40, 10, 11, 9 };
    int x = 1;
    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[] = { 1, 3, 5, 7, 9, 8 };
        int search = liner(
            arr,
            10); // 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 = { 1, 3, 5, 7, 9, 8 };
    int search = liner(arr, 10); // 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

BINARY SEARCHING EXAMPLE:

C++




#include <iostream>
using namespace std;
 
int binarySearch(int array[], int x, int low, int high)
{
 
    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 GFG(void)
{
    int array[] = {
 
#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;
    }
 
    int main(void)
    {
        int array[] = { 2, 4, 5, 17, 14, 7, 11, 22 };
        int x = 22;
        int n = sizeof(array) / sizeof(array[0]);
        int result = binarySearch(array, x, 0, n - 1);
        if (result == -1)
            printf("Not found");
        else
            printf("Element is found at index %d", result);
    }
};
int x = 4;
int n = sizeof(array) / sizeof(array[0]);
int result = binarySearch(array, x, 0, n - 1);
if (result == -1)
    printf("Not found");
else
    printf("Element is found at index %d", result);
}

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 GFG(void)
{
    int array[] = { 2, 4, 5, 17, 14, 7, 11, 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("Element is found at index %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, 17, 14, 7, 11, 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, 17, 14, 7, 11, 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, 17, 14, 7, 11, 22 };
    int search = binary(arr, 22);
    Console.Write(search);
  }
}
// This code is contributed by aditya942003patil


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!