- Blog Categories
- Software Development
- Data Science
- AI/ML
- Marketing
- General
- MBA
- Management
- Legal
- Software Development Projects and Ideas
- 12 Computer Science Project Ideas
- 28 Beginner Software Projects
- Top 10 Engineering Project Ideas
- Top 10 Easy Final Year Projects
- Top 10 Mini Projects for Engineers
- 25 Best Django Project Ideas
- Top 20 MERN Stack Project Ideas
- Top 12 Real Time Projects
- Top 6 Major CSE Projects
- 12 Robotics Projects for All Levels
- Java Programming Concepts
- Abstract Class in Java and Methods
- Constructor Overloading in Java
- StringBuffer vs StringBuilder
- Java Identifiers: Syntax & Examples
- Types of Variables in Java Explained
- Composition in Java: Examples
- Append in Java: Implementation
- Loose Coupling vs Tight Coupling
- Integrity Constraints in DBMS
- Different Types of Operators Explained
- Career and Interview Preparation in IT
- Top 14 IT Courses for Jobs
- Top 20 Highest Paying Languages
- 23 Top CS Interview Q&A
- Best IT Jobs without Coding
- Software Engineer Salary in India
- 44 Agile Methodology Interview Q&A
- 10 Software Engineering Challenges
- Top 15 Tech's Daily Life Impact
- 10 Best Backends for React
- Cloud Computing Reference Models
- Web Development and Security
- Find Installed NPM Version
- Install Specific NPM Package Version
- Make API Calls in Angular
- Install Bootstrap in Angular
- Use Axios in React: Guide
- StrictMode in React: Usage
- 75 Cyber Security Research Topics
- Top 7 Languages for Ethical Hacking
- Top 20 Docker Commands
- Advantages of OOP
- Data Science Projects and Applications
- 42 Python Project Ideas for Beginners
- 13 Data Science Project Ideas
- 13 Data Structure Project Ideas
- 12 Real-World Python Applications
- Python Banking Project
- Data Science Course Eligibility
- Association Rule Mining Overview
- Cluster Analysis in Data Mining
- Classification in Data Mining
- KDD Process in Data Mining
- Data Structures and Algorithms
- Binary Tree Types Explained
- Binary Search Algorithm
- Sorting in Data Structure
- Binary Tree in Data Structure
- Binary Tree vs Binary Search Tree
- Recursion in Data Structure
- Data Structure Search Methods: Explained
- Binary Tree Interview Q&A
- Linear vs Binary Search
- Priority Queue Overview
- Python Programming and Tools
- Top 30 Python Pattern Programs
- List vs Tuple
- Python Free Online Course
- Method Overriding in Python
- Top 21 Python Developer Skills
- Reverse a Number in Python
- Switch Case Functions in Python
- Info Retrieval System Overview
- Reverse a Number in Python
- Real-World Python Applications
- Data Science Careers and Comparisons
- Data Analyst Salary in India
- Data Scientist Salary in India
- Free Excel Certification Course
- Actuary Salary in India
- Data Analyst Interview Guide
- Pandas Interview Guide
- Tableau Filters Explained
- Data Mining Techniques Overview
- Data Analytics Lifecycle Phases
- Data Science Vs Analytics Comparison
- Artificial Intelligence and Machine Learning Projects
- Exciting IoT Project Ideas
- 16 Exciting AI Project Ideas
- 45+ Interesting ML Project Ideas
- Exciting Deep Learning Projects
- 12 Intriguing Linear Regression Projects
- 13 Neural Network Projects
- 5 Exciting Image Processing Projects
- Top 8 Thrilling AWS Projects
- 12 Engaging AI Projects in Python
- NLP Projects for Beginners
- Concepts and Algorithms in AIML
- Basic CNN Architecture Explained
- 6 Types of Regression Models
- Data Preprocessing Steps
- Bagging vs Boosting in ML
- Multinomial Naive Bayes Overview
- Gini Index for Decision Trees
- Bayesian Network Example
- Bayes Theorem Guide
- Top 10 Dimensionality Reduction Techniques
- Neural Network Step-by-Step Guide
- Technical Guides and Comparisons
- Make a Chatbot in Python
- Compute Square Roots in Python
- Permutation vs Combination
- Image Segmentation Techniques
- Generative AI vs Traditional AI
- AI vs Human Intelligence
- Random Forest vs Decision Tree
- Neural Network Overview
- Perceptron Learning Algorithm
- Selection Sort Algorithm
- Career and Practical Applications in AIML
- AI Salary in India Overview
- Biological Neural Network Basics
- Top 10 AI Challenges
- Production System in AI
- Top 8 Raspberry Pi Alternatives
- Top 8 Open Source Projects
- 14 Raspberry Pi Project Ideas
- 15 MATLAB Project Ideas
- Top 10 Python NLP Libraries
- Naive Bayes Explained
- Digital Marketing Projects and Strategies
- 10 Best Digital Marketing Projects
- 17 Fun Social Media Projects
- Top 6 SEO Project Ideas
- Digital Marketing Case Studies
- Coca-Cola Marketing Strategy
- Nestle Marketing Strategy Analysis
- Zomato Marketing Strategy
- Monetize Instagram Guide
- Become a Successful Instagram Influencer
- 8 Best Lead Generation Techniques
- Digital Marketing Careers and Salaries
- Digital Marketing Salary in India
- Top 10 Highest Paying Marketing Jobs
- Highest Paying Digital Marketing Jobs
- SEO Salary in India
- Brand Manager Salary in India
- Content Writer Salary Guide
- Digital Marketing Executive Roles
- Career in Digital Marketing Guide
- Future of Digital Marketing
- MBA in Digital Marketing Overview
- Digital Marketing Techniques and Channels
- 9 Types of Digital Marketing Channels
- Top 10 Benefits of Marketing Branding
- 100 Best YouTube Channel Ideas
- YouTube Earnings in India
- 7 Reasons to Study Digital Marketing
- Top 10 Digital Marketing Objectives
- 10 Best Digital Marketing Blogs
- Top 5 Industries Using Digital Marketing
- Growth of Digital Marketing in India
- Top Career Options in Marketing
- Interview Preparation and Skills
- 73 Google Analytics Interview Q&A
- 56 Social Media Marketing Q&A
- 78 Google AdWords Interview Q&A
- Top 133 SEO Interview Q&A
- 27+ Digital Marketing Q&A
- Digital Marketing Free Course
- Top 9 Skills for PPC Analysts
- Movies with Successful Social Media Campaigns
- Marketing Communication Steps
- Top 10 Reasons to Be an Affiliate Marketer
- Career Options and Paths
- Top 25 Highest Paying Jobs India
- Top 25 Highest Paying Jobs World
- Top 10 Highest Paid Commerce Job
- Career Options After 12th Arts
- Top 7 Commerce Courses Without Maths
- Top 7 Career Options After PCB
- Best Career Options for Commerce
- Career Options After 12th CS
- Top 10 Career Options After 10th
- 8 Best Career Options After BA
- Projects and Academic Pursuits
- 17 Exciting Final Year Projects
- Top 12 Commerce Project Topics
- Top 13 BCA Project Ideas
- Career Options After 12th Science
- Top 15 CS Jobs in India
- 12 Best Career Options After M.Com
- 9 Best Career Options After B.Sc
- 7 Best Career Options After BCA
- 22 Best Career Options After MCA
- 16 Top Career Options After CE
- Courses and Certifications
- 10 Best Job-Oriented Courses
- Best Online Computer Courses
- Top 15 Trending Online Courses
- Top 19 High Salary Certificate Courses
- 21 Best Programming Courses for Jobs
- What is SGPA? Convert to CGPA
- GPA to Percentage Calculator
- Highest Salary Engineering Stream
- 15 Top Career Options After Engineering
- 6 Top Career Options After BBA
- Job Market and Interview Preparation
- Why Should You Be Hired: 5 Answers
- Top 10 Future Career Options
- Top 15 Highest Paid IT Jobs India
- 5 Common Guesstimate Interview Q&A
- Average CEO Salary: Top Paid CEOs
- Career Options in Political Science
- Top 15 Highest Paying Non-IT Jobs
- Cover Letter Examples for Jobs
- Top 5 Highest Paying Freelance Jobs
- Top 10 Highest Paying Companies India
- Career Options and Paths After MBA
- 20 Best Careers After B.Com
- Career Options After MBA Marketing
- Top 14 Careers After MBA In HR
- Top 10 Highest Paying HR Jobs India
- How to Become an Investment Banker
- Career Options After MBA - High Paying
- Scope of MBA in Operations Management
- Best MBA for Working Professionals India
- MBA After BA - Is It Right For You?
- Best Online MBA Courses India
- MBA Project Ideas and Topics
- 11 Exciting MBA HR Project Ideas
- Top 15 MBA Project Ideas
- 18 Exciting MBA Marketing Projects
- MBA Project Ideas: Consumer Behavior
- What is Brand Management?
- What is Holistic Marketing?
- What is Green Marketing?
- Intro to Organizational Behavior Model
- Tech Skills Every MBA Should Learn
- Most Demanding Short Term Courses MBA
- MBA Salary, Resume, and Skills
- MBA Salary in India
- HR Salary in India
- Investment Banker Salary India
- MBA Resume Samples
- Sample SOP for MBA
- Sample SOP for Internship
- 7 Ways MBA Helps Your Career
- Must-have Skills in Sales Career
- 8 Skills MBA Helps You Improve
- Top 20+ SAP FICO Interview Q&A
- MBA Specializations and Comparative Guides
- Why MBA After B.Tech? 5 Reasons
- How to Answer 'Why MBA After Engineering?'
- Why MBA in Finance
- MBA After BSc: 10 Reasons
- Which MBA Specialization to choose?
- Top 10 MBA Specializations
- MBA vs Masters: Which to Choose?
- Benefits of MBA After CA
- 5 Steps to Management Consultant
- 37 Must-Read HR Interview Q&A
- Fundamentals and Theories of Management
- What is Management? Objectives & Functions
- Nature and Scope of Management
- Decision Making in Management
- Management Process: Definition & Functions
- Importance of Management
- What are Motivation Theories?
- Tools of Financial Statement Analysis
- Negotiation Skills: Definition & Benefits
- Career Development in HRM
- Top 20 Must-Have HRM Policies
- Project and Supply Chain Management
- Top 20 Project Management Case Studies
- 10 Innovative Supply Chain Projects
- Latest Management Project Topics
- 10 Project Management Project Ideas
- 6 Types of Supply Chain Models
- Top 10 Advantages of SCM
- Top 10 Supply Chain Books
- What is Project Description?
- Top 10 Project Management Companies
- Best Project Management Courses Online
- Salaries and Career Paths in Management
- Project Manager Salary in India
- Average Product Manager Salary India
- Supply Chain Management Salary India
- Salary After BBA in India
- PGDM Salary in India
- Top 7 Career Options in Management
- CSPO Certification Cost
- Why Choose Product Management?
- Product Management in Pharma
- Product Design in Operations Management
- Industry-Specific Management and Case Studies
- Amazon Business Case Study
- Service Delivery Manager Job
- Product Management Examples
- Product Management in Automobiles
- Product Management in Banking
- Sample SOP for Business Management
- Video Game Design Components
- Top 5 Business Courses India
- Free Management Online Course
- SCM Interview Q&A
- Fundamentals and Types of Law
- Acceptance in Contract Law
- Offer in Contract Law
- 9 Types of Evidence
- Types of Law in India
- Introduction to Contract Law
- Negotiable Instrument Act
- Corporate Tax Basics
- Intellectual Property Law
- Workmen Compensation Explained
- Lawyer vs Advocate Difference
- Law Education and Courses
- LLM Subjects & Syllabus
- Corporate Law Subjects
- LLM Course Duration
- Top 10 Online LLM Courses
- Online LLM Degree
- Step-by-Step Guide to Studying Law
- Top 5 Law Books to Read
- Why Legal Studies?
- Pursuing a Career in Law
- How to Become Lawyer in India
- Career Options and Salaries in Law
- Career Options in Law India
- Corporate Lawyer Salary India
- How To Become a Corporate Lawyer
- Career in Law: Starting, Salary
- Career Opportunities: Corporate Law
- Business Lawyer: Role & Salary Info
- Average Lawyer Salary India
- Top Career Options for Lawyers
- Types of Lawyers in India
- Steps to Become SC Lawyer in India
- Tutorials
- Software Tutorials
- C Tutorials
- Recursion in C: Fibonacci Series
- Checking String Palindromes in C
- Prime Number Program in C
- Implementing Square Root in C
- Matrix Multiplication in C
- Understanding Double Data Type
- Factorial of a Number in C
- Structure of a C Program
- Building a Calculator Program in C
- Compiling C Programs on Linux
- Java Tutorials
- Handling String Input in Java
- Determining Even and Odd Numbers
- Prime Number Checker
- Sorting a String
- User-Defined Exceptions
- Understanding the Thread Life Cycle
- Swapping Two Numbers
- Using Final Classes
- Area of a Triangle
- Skills
- Explore Skills
- Management Skills
- Software Engineering
- JavaScript
- Data Structure
- React.js
- Core Java
- Node.js
- Blockchain
- SQL
- Full stack development
- Devops
- NFT
- BigData
- Cyber Security
- Cloud Computing
- Database Design with MySQL
- Cryptocurrency
- Python
- Digital Marketings
- Advertising
- Influencer Marketing
- Search Engine Optimization
- Performance Marketing
- Search Engine Marketing
- Email Marketing
- Content Marketing
- Social Media Marketing
- Display Advertising
- Marketing Analytics
- Web Analytics
- Affiliate Marketing
- MBA
- MBA in Finance
- MBA in HR
- MBA in Marketing
- MBA in Business Analytics
- MBA in Operations Management
- MBA in International Business
- MBA in Information Technology
- MBA in Healthcare Management
- MBA In General Management
- MBA in Agriculture
- MBA in Supply Chain Management
- MBA in Entrepreneurship
- MBA in Project Management
- Management Program
- Consumer Behaviour
- Supply Chain Management
- Financial Analytics
- Introduction to Fintech
- Introduction to HR Analytics
- Fundamentals of Communication
- Art of Effective Communication
- Introduction to Research Methodology
- Mastering Sales Technique
- Business Communication
- Fundamentals of Journalism
- Economics Masterclass
- Free Courses
Linear Search vs Binary Search: Key Differences Explained Simply
Updated on 21 November, 2024
67.54K+ views
• 18 min read
Table of Contents
- What is a Linear Search?
- What is Binary Search?
- Differences Between Linear Search and Binary Search
- Advantages and Disadvantages of Linear and Binary Search
- Linear Search Algorithm: Steps and Syntax
- Time Complexity of Binary Search
- Binary Search Algorithm: Steps and Syntax
- Use Cases: When to Use Linear Search vs Binary Search
- Explore upGrad’s Data Science Courses
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
- Begin at the first element of the array or list.
- Compare each element with the target value.
- If a match is found, return the position of the element.
- 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:
- Start by comparing the target element with the middle element of the sorted array.
- If the target matches the middle element, the search ends successfully.
- If the target is smaller than the middle element, search in the left half of the array.
- If the target is larger than the middle element, search in the right half of the array.
- 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
- Best Case: O(1)
- The search is successful in the first comparison.
- Example: The target element is at index 0.
- Worst Case: O(n)
- The search iterates through the entire list.
- Example: The target is at the last index or absent in the dataset.
- 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.
- 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
Start at the First Element:
Compare the target value with the first element in the array.
Sequential Comparison:
If the first element is not the target, move to the next element and compare.
Repeat Until Found or End:
Continue this process until the target element is found or the end of the list is reached.
- 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 (low, high, 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
- Initialize Pointers:
- Start with two pointers: low (beginning of the array) and high (end of the array).
- Calculate the Midpoint:
- Compute the middle index as mid = (low + high) / 2 (or equivalent for integer division).
- 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).
- Repeat:
- Continue dividing and searching until the target is found or low > high.
- 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.
Explore our Popular Data Science Courses
Unlock expert insights with our Popular Data Science Articles, covering the latest trends and techniques. From analytics to innovation, we’ve got you covered!
Read our popular Data Science Articles
Boost your career prospects with the Top Data Science Skills to Learn, essential for navigating the future of analytics and AI!
Top Data Science Skills to Learn
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.