Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Linear Search vs Binary Search: Key Differences Explained Simply

Updated on 21 November, 2024

67.54K+ views
18 min read

Search algorithms in data structure is a core concept in programming that helps locate an element within a dataset. As developers, being aware of which search algorithm to use can significantly impact the efficiency of our programs. Two popular search methods are linear search and binary search, each suited to different use cases. The difference between linear search and binary search lies in their approach and performance.

Linear search is simple and checks each element one by one until it finds the desired item or reaches the end of the list. Binary search, however, is faster but works only on sorted datasets by repeatedly dividing the search range into halves.

In this blog, we’ll explore the difference between linear search and binary search in detail, discuss their time complexities, and learn when to use each method.

To fully grasp these concepts, it’s important to have a solid foundation in data structures. This guide walks you through the essentials.

What is a Linear Search?

Linear search, also known as sequential search, is one of the simplest algorithms used to find the position of a target element in a list or array. It works by scanning each element one by one, starting from the first index, until the desired element is found or the list ends. This algorithm is suitable for both sorted and unsorted data.

How Linear Search Works

  1. Begin at the first element of the array or list.
  2. Compare each element with the target value.
  3. If a match is found, return the position of the element.
  4. If the end of the list is reached without finding a match, return -1.

Linear search does not skip elements and ensures that all possible matches are checked. However, it can be inefficient for large datasets due to its O(n) time complexity in the worst case.

Begin Search at Index 0: Start from the first element (arr[0] = 10).

  • Compare 10 with 5. No match, move to the next index.

Continue Sequential Comparisons:

  • arr[1] = 8: No match.
  • arr[2] = 1: No match.
  • arr[3] = 21: No match.
  • arr[4] = 7: No match.
  • arr[5] = 32: No match.

Find Match at Index 6:

  • At arr[6] = 5, the search key matches the element in the array.
  • Stop the search process immediately.

Result:

  • The element 5 is found at index 6.
  • Return the index position 6 as the result.

You might also find this helpful: A free Python course that comes with certification.

What is Binary Search?

Binary search is an efficient search algorithm that repeatedly divides a sorted dataset into halves to find the position of a target element. Unlike linear search, which checks each element sequentially, binary search narrows down the search area by comparing the target with the middle element of the dataset. This approach significantly reduces the number of comparisons, making it faster and more suitable for large datasets, provided they are sorted.

How Binary Search Works

Binary search operates on the divide and conquer principle. Here's the step-by-step explanation:

  1. Start by comparing the target element with the middle element of the sorted array.
  2. If the target matches the middle element, the search ends successfully.
  3. If the target is smaller than the middle element, search in the left half of the array.
  4. If the target is larger than the middle element, search in the right half of the array.
  5. Repeat the process until the target is found or the search space is exhausted.

Start the Search:

  • Begin with the entire sorted array {10, 14, 19, 26, 27, 31, 33, 35, 42, 44}.
  • Initial Range: Set low = 0 (start of the array) and high = 9 (end of the array).

First Comparison:

  • Calculate Middle Index: mid = (low + high) / 2 = (0 + 9) / 2 = 4.
  • Check Middle Element: arr[4] = 27.
  • Compare with Target (33):
    • 33 > 27 → Target is in the right sub-array.
    • Update Range: Set low = mid + 1 = 5.

Second Comparison:

  • Recalculate Middle Index: mid = (low + high) / 2 = (5 + 9) / 2 = 7.
  • Check Middle Element: arr[7] = 33.
  • Compare with Target (33):
    • 33 == 33 → Target found at index 7.
    • Stop Search: Return index 7.

Differences Between Linear Search and Binary Search

Linear search and binary search are two fundamental search algorithms with distinct approaches, data requirements, and efficiency levels. Here's a breakdown of their differences:

Basis of Comparison

Linear Search

Binary Search

Definition

Sequentially checks each element in the list.

Divides the dataset into halves to locate the target.

Data Requirements

Works on both sorted and unsorted data.

Requires the data to be sorted beforehand.

Approach

Scans elements one by one from start to end.

Compares the target with the middle element and narrows down the search range.

Time Complexity

O(n)

O(log n)

Space Complexity

O(1)

O(1) for iterative, O(log n) for recursive.

Efficiency

Inefficient for large datasets.

Highly efficient for large datasets.

Best Case

Target is the first element (O(1)).

Target is the middle element (O(1)).

Worst Case

Target is the last element or not in the list (O(n)).

Target is not present, requiring maximum halving (O(log n)).

Use Cases

Searching in small or unsorted datasets.

Searching in large, sorted datasets.

Applications

Useful in scenarios where data changes frequently.

Ideal for static datasets where sorting is feasible.

Advantages and Disadvantages of Linear and Binary Search

Search Algorithm

Advantages

Disadvantages

Linear Search

- Works on both sorted and unsorted datasets.

- Inefficient for large datasets due to O(n) time complexity.

 

- Simple to implement with minimal coding effort.

- No early termination; checks all elements until the end.

 

- Compatible with various data structures, such as arrays and linked lists.

- Cannot leverage patterns in data for optimization.

 

- Ideal for small datasets or scenarios where sorting is unnecessary.

- Unsuitable for time-sensitive applications with large datasets.

Binary Search

- Extremely fast for large datasets with O(log n) time complexity.

- Requires the dataset to be sorted, adding preprocessing overhead.

 

- Efficient for static datasets where sorting remains unchanged over time.

- Cannot be applied to unsorted or dynamically changing datasets.

 

- Uses a divide-and-conquer approach, significantly reducing the number of comparisons.

- Incompatible with linked lists due to lack of direct access to middle elements.

 

- Early termination possible, saving computational time when the target is not in the dataset.

- More complex to implement compared to linear search.

 

- Ideal for applications like database searches, large log files, and sorted static datasets.

- Limited to sequential access memory structures such as arrays.

Time Complexity of Linear Search

Linear search is a straightforward algorithm that examines each element in a list one by one to find a target value. As the size of the dataset increases, the time required to find the target also increases proportionally. Here’s a detailed look at its complexity:

Complexity Analysis of Linear Search

  1. Best Case: O(1)
    • The search is successful in the first comparison.
    • Example: The target element is at index 0.
  2. Worst Case: O(n)
    • The search iterates through the entire list.
    • Example: The target is at the last index or absent in the dataset.
  3. Average Case: O(n)
    • On average, the search will find the element somewhere in the middle of the list. It will perform n/2 comparisons but is represented as O(n) for asymptotic analysis.
  4. Space Complexity: O(1)
    • Linear search operates directly on the input array without requiring additional memory, making it space-efficient.

Example to Illustrate Complexity

Find the number 13 in the array {1, 3, 5, 7, 9, 11, 13} using linear search.

Code Example:

java

public class LinearSearchDemo {
    public static int linearSearch(int[] array, int target) {
        for (int i = 0; i < array.length; i++) {
            if (array[i] == target) {
                return i; // Target found
            }
        }
        return -1; // Target not found
    }

    public static void main(String[] args) {
        int[] numbers = {1, 3, 5, 7, 9, 11, 13};
        int target = 13;
        int result = linearSearch(numbers, target);

        if (result == -1) {
            System.out.println("Element not found.");
        } else {
            System.out.println("Element found at index: " + result);
        }
    }
}

Output:

mathematica

Element found at index: 6

The output indicates that the target element (13) was successfully located in the array at index 6

Linear Search Algorithm: Steps and Syntax

Linear search is a straightforward algorithm for finding an element in a list. It works by sequentially checking each element until the target is found or the list ends.

Steps of the Linear Search Algorithm

  1. Start at the First Element:

    Compare the target value with the first element in the array.

  2. Sequential Comparison:

    If the first element is not the target, move to the next element and compare.

  3. Repeat Until Found or End:

    Continue this process until the target element is found or the end of the list is reached.

  4. Return the Result:
    • If the element is found, return its index.
    • If not, return -1 to indicate that the element is not present.

Code Examples in Different Languages

1. C++: Linear Search Syntax

The program searches for the target 30 in the array {10, 20, 30, 40, 50}.

cpp

#include <iostream>
using namespace std;

int linearSearch(int arr[], int n, int target) {
    for (int i = 0; i < n; i++) {
        if (arr[i] == target) {
            return i; // Element found, return index
        }
    }
    return -1; // Element not found
}

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 30;
    
    int result = linearSearch(arr, n, target);
    if (result == -1) {
        cout << "Element not found." << endl;
    } else {
        cout << "Element found at index: " << result << endl;
    }
    return 0;
}

Output:

mathematica

Element found at index: 2

2. Java: Linear Search Syntax

The program searches for the target 15 in the array {5, 10, 15, 20, 25}.

java

public class LinearSearch {
    public static int linearSearch(int[] array, int target) {
        for (int i = 0; i < array.length; i++) {
            if (array[i] == target) {
                return i; // Return index of the target
            }
        }
        return -1; // Element not found
    }

    public static void main(String[] args) {
        int[] arr = {5, 10, 15, 20, 25};
        int target = 15;
        int result = linearSearch(arr, target);
        
        if (result == -1) {
            System.out.println("Element not found.");
        } else {
            System.out.println("Element found at index: " + result);
        }
    }
}

Output:

mathematica

Element found at index: 2

3. Python: Linear Search Syntax

The program searches for the target 6 in the array [2, 4, 6, 8, 10].

python

def linear_search(arr, target):
    for i in range(len(arr)):
        if arr[i] == target:
            return i  # Return index of the target
    return -1  # Element not found

# Main program
arr = [2, 4, 6, 8, 10]
target = 6

result = linear_search(arr, target)
if result == -1:
    print("Element not found.")
else:
    print(f"Element found at index: {result}")

Output:

mathematica

Element found at index: 2

Example: Searching an Element in an Array

Find the position of a target number, 13, in the unsorted integer array {10, 23, 45, 13, 67, 89, 13, 99} using linear search.

java

public class LinearSearchExample {
    // Linear search method
    public static int linearSearch(int[] array, int target) {
        for (int i = 0; i < array.length; i++) {
            if (array[i] == target) {
                return i; // Return the index if the target is found
            }
        }
        return -1; // Return -1 if the target is not found
    }

    public static void main(String[] args) {
        // Array of integers
        int[] numbers = {10, 23, 45, 13, 67, 89, 13, 99};
        int target = 13; // Element to search
        int position = linearSearch(numbers, target);

        // Output results
        if (position == -1) {
            System.out.println("Element not found.");
        } else {
            System.out.println("Element found at index: " + position);
        }
    }
}

Output

mathematica

Element found at index: 3

Time Complexity of Binary Search

Binary search is known for its efficiency in handling large datasets due to its divide-and-conquer approach. The algorithm significantly reduces the search space by half with each step, which it faster than linear search for sorted data. Let’s see the time and space complexity analysis:

Time Complexity Analysis

  • Best Case: O(1)
    • The search is completed in one step when the target element is the middle element of the array.
    • Example: In the sorted array [10, 20, 30, 40, 50], searching for 30 directly matches the middle element.
  • Worst Case: O(log n)
    • The dataset is halved repeatedly until the target is found or the search space is exhausted.
    • Example: Searching for 5 or 60 in [10, 20, 30, 40, 50] requires dividing the array multiple times.

Space Complexity Analysis

  • Iterative Version: O(1)
    • No extra memory is required as the algorithm uses a fixed number of variables for tracking pointers (lowhigh, and mid).
  • Recursive Version: O(log n)
    • Additional memory is consumed due to recursive function calls, as each call adds to the stack.

Binary Search Algorithm: Steps and Syntax

Binary search is an efficient search algorithm for sorted arrays. It divides the search space in half during each step, significantly reducing the number of comparisons required.

Steps to Perform Binary Search

  1. Initialize Pointers:
    • Start with two pointers: low (beginning of the array) and high (end of the array).
  2. Calculate the Midpoint:
    • Compute the middle index as mid = (low + high) / 2 (or equivalent for integer division).
  3. Compare the Middle Element:
    • If array[mid] == target: Return mid (target found).
    • If array[mid] < target: Shift the low pointer to mid + 1 (search in the right half).
    • If array[mid] > target: Shift the high pointer to mid - 1 (search in the left half).
  4. Repeat:
    • Continue dividing and searching until the target is found or low > high.
  5. Result:
    • If the target is not found, return -1.

Code Examples in Different Languages

1. C++: Binary Search Syntax

The program searches for the target 30 in the sorted array {10, 20, 30, 40, 50}.

cpp

#include <iostream>
using namespace std;

int binarySearch(int arr[], int size, int target) {
    int low = 0, high = size - 1;

    while (low <= high) {
        int mid = low + (high - low) / 2; // Calculate mid-point
        if (arr[mid] == target) {
            return mid; // Target found
        } else if (arr[mid] < target) {
            low = mid + 1; // Search right half
        } else {
            high = mid - 1; // Search left half
        }
    }
    return -1; // Target not found
}

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int size = sizeof(arr) / sizeof(arr[0]);
    int target = 30;

    int result = binarySearch(arr, size, target);
    if (result == -1) {
        cout << "Element not found." << endl;
    } else {
        cout << "Element found at index: " << result << endl;
    }

    return 0;
}

Output:

mathematica

Element found at index: 2

2. Java: Binary Search Syntax

The program searches for the target 40 in the sorted array {10, 20, 30, 40, 50}.

java

public class BinarySearchExample {
    public static int binarySearch(int[] array, int target) {
        int low = 0, high = array.length - 1;

        while (low <= high) {
            int mid = low + (high - low) / 2; // Calculate mid-point
            if (array[mid] == target) {
                return mid; // Target found
            } else if (array[mid] < target) {
                low = mid + 1; // Search right half
            } else {
                high = mid - 1; // Search left half
            }
        }
        return -1; // Target not found
    }

    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};
        int target = 40;

        int result = binarySearch(numbers, target);
        if (result == -1) {
            System.out.println("Element not found.");
        } else {
            System.out.println("Element found at index: " + result);
        }
    }
}

Output:

mathematica

Element found at index: 3

upGrad’s Exclusive Data Science Webinar for you –

The Future of Consumer Data in an Open Data Economy

 

 

3. Python: Binary Search Syntax

The program searches for the target 50 in the sorted array [10, 20, 30, 40, 50].

python

def binary_search(arr, target):
    low, high = 0, len(arr) - 1

    while low <= high:
        mid = (low + high) // 2  # Calculate mid-point
        if arr[mid] == target:
            return mid  # Target found
        elif arr[mid] < target:
            low = mid + 1  # Search right half
        else:
            high = mid - 1  # Search left half

    return -1  # Target not found

# Example usage
arr = [10, 20, 30, 40, 50]
target = 50

result = binary_search(arr, target)
if result == -1:
    print("Element not found.")
else:
    print(f"Element found at index: {result}")

Output:

mathematica

Element found at index: 4

Example in Practice: Binary Search for Finding a Product ID

Search for the product ID 67 in the sorted array {12, 24, 35, 47, 56, 67, 78, 89} using binary search.

Code Example:

java

public class ProductSearch {
    public static int binarySearch(int[] productIDs, int target) {
        int low = 0, high = productIDs.length - 1;

        while (low <= high) {
            int mid = low + (high - low) / 2; // Calculate mid-point
            if (productIDs[mid] == target) {
                return mid; // Target found
            } else if (productIDs[mid] < target) {
                low = mid + 1; // Search right half
            } else {
                high = mid - 1; // Search left half
            }
        }
        return -1; // Target not found
    }

    public static void main(String[] args) {
        int[] productIDs = {12, 24, 35, 47, 56, 67, 78, 89};
        int target = 67;

        int result = binarySearch(productIDs, target);
        if (result == -1) {
            System.out.println("Product ID not found.");
        } else {
            System.out.println("Product ID found at index: " + result);
        }
    }
}

Output:

mathematica

Product ID found at index: 5

Binary Search Example: Finding the Grade of a Student

Search for a specific grade (85) in a sorted array of grades {50, 60, 70, 80, 85, 90, 95, 100} using binary search.

Code Example:

java

public class GradeSearch {
    public static int binarySearch(int[] grades, int target) {
        int low = 0, high = grades.length - 1;

        while (low <= high) {
            int mid = low + (high - low) / 2; // Calculate mid-point
            if (grades[mid] == target) {
                return mid; // Target found
            } else if (grades[mid] < target) {
                low = mid + 1; // Search the right half
            } else {
                high = mid - 1; // Search the left half
            }
        }
        return -1; // Target not found
    }

    public static void main(String[] args) {
        int[] grades = {50, 60, 70, 80, 85, 90, 95, 100};
        int target = 85;

        int result = binarySearch(grades, target);
        if (result == -1) {
            System.out.println("Grade not found.");
        } else {
            System.out.println("Grade found at index: " + result);
        }
    }
}

Output:

perl

Grade found at index: 4

Use Cases: When to Use Linear Search vs Binary Search

When to Use Linear Search

Linear search is best suited for situations where simplicity and flexibility are more important than speed.

  • Unsorted Data:

    Linear search works well when the dataset is unsorted or dynamic. For example, searching for a specific customer ID in a temporary list of 20 records is more practical with linear search since no sorting is required.

  • Small Datasets:

    For small datasets (e.g., fewer than 50 elements), the overhead of sorting for binary search outweighs the simplicity of linear search. For example, finding a missing item in a grocery list of 15 products.

  • Checking Specific Conditions:

    Linear search is ideal for conditions like finding the first occurrence of an element satisfying a condition. For example, identifying the first even number in an array of 10 integers: {3, 7, 10, 15, 18}.

  • Dynamic or Frequently Changing Data:

    If the dataset changes frequently and sorting it after every modification is impractical, linear search is the go-to solution.

  • Data Structures:

    Suitable for linked lists or unsorted arrays where accessing elements by index is not straightforward.

Example: Searching for the number 5 in an unsorted list of 100 elements. Linear search will scan each element sequentially, taking up to 100 comparisons in the worst case.

When to Use Binary Search

Binary search is the algorithm of choice for large datasets where performance is critical and the data is sorted.

  • Sorted Data:

    Binary search is highly efficient when working with pre-sorted datasets. For example, it can be used to find a specific book in a library catalog sorted alphabetically by title.

  • Large Datasets:

    Binary search significantly reduces search time for datasets larger than 1,000 elements. For example, searching for a product ID in a database with 10,000 entries requires a maximum of only 14 comparisons (214=16,3842^{14} = 16,384214=16,384).

  • Static Data:

    Ideal for scenarios where data does not change frequently. Sorting can be done once, and binary search can be applied repeatedly. Example: Searching in historical weather data.

  • Applications in Databases:

    Binary search is used in databases for index-based retrieval. For example, finding a customer record in a sorted database with millions of entries can be done in logarithmic time.

  • Efficient Search Needs:

    This product works well for applications that require frequent search operations, such as autocomplete suggestions in search engines or user ID lookups in authentication systems.

Example: Searching for a student’s roll number in a sorted list of 10,000 students. Binary search will require 14 steps, compared to up to 10,000 for linear search.

Explore upGrad’s Data Science Courses

Build a strong foundation in data science with upGrad’s programs designed for real-world application. 

Learn key topics like search algorithms, data structures, and analytics through practical projects. 

These courses, created with leading universities, cover data science, machine learning, and AI.

Why Choose upGrad?

  • Curriculum includes the latest AI advancements.
  • Hands-on training with cutting-edge tools.
  • Alumni report an average 57% salary increase.
  • Access 1:1 mentorship and exclusive job opportunities.

Start your journey today and gain skills that make you stand out in the data-driven world.

Start your career in tech with software development courses from top universities.

Learn from the best with our Popular Data Science Courses and become a sought-after data professional.

Unlock expert insights with our Popular Data Science Articles, covering the latest trends and techniques. From analytics to innovation, we’ve got you covered!

Boost your career prospects with the Top Data Science Skills to Learn, essential for navigating the future of analytics and AI!

Frequently Asked Questions (FAQs)

1. Can binary search work on unsorted data?

No, binary search cannot work on unsorted data. It requires the dataset to be sorted in ascending or descending order to divide the search space effectively.

2. Why is binary search faster than linear search?

Binary search is faster because it reduces the search space by half in each step, following a divide-and-conquer approach. Linear search, on the other hand, checks each element sequentially, making it slower for large datasets.

3. What are the applications of linear search?

Linear search is used when the data is unsorted or dynamic, such as searching for a specific item in an inventory list, looking up a value in an array, or finding an element in a linked list.

4. Can binary search be implemented on linked lists?

Binary search is unsuitable for linked lists because it requires direct access to the middle element, which linked lists do not provide. Traversing a linked list to find the middle element would eliminate the efficiency of binary search.

5. Which search is better for small datasets?

Linear search is better for small datasets because it is simple to implement and doesn’t require sorting the data, saving preprocessing time.

6. How does the time complexity of linear search differ from binary search?

Linear search has a time complexity of O(n) as it checks each element, whereas binary search has a time complexity of O(log n) because it halves the search space at each step.

7. When is the best case for linear search?

The best case for linear search occurs when the target element is the first element in the dataset, resulting in a time complexity of O(1).

8. Why does binary search require a sorted array?

Binary search needs a sorted array to determine which half of the dataset may contain the target element. Without sorting, the algorithm cannot effectively divide the data.

9. What is the space complexity of binary search?

The space complexity of binary search is O(1) for the iterative approach, as it only uses a few variables for indexing. For the recursive approach, the space complexity is O(log n) due to the function call stack.

10. How do linear and binary searches differ in terms of approach?

Linear search sequentially checks each element, making it simple but slow for large datasets. Binary search divides the dataset in half repeatedly, requiring sorting but being much faster for large datasets.

11. Which search algorithm is commonly used in databases?

Binary search is commonly used in databases with sorted indexes to quickly retrieve records, making it ideal for structured and large-scale data storage.