Linear Search — Examine Items Sequentially
Binary Search — Eliminate Half of the Remaining List
Finding information is one of the most common tasks performed by computer programs. Whether an application is looking for a customer’s name, checking a product inventory, locating a student record, or searching through stored numbers, it needs a method for identifying the required item.
Linear search and binary search are two fundamental algorithms that solve this problem using very different approaches.
Linear search examines items one at a time until it finds the target. Binary search repeatedly divides a sorted search range into smaller sections, eliminating possibilities after each comparison.
Although binary search is generally much faster for large sorted arrays, linear search remains valuable because it works with unsorted information and requires very little preparation.
Understanding both algorithms provides a practical introduction to computational efficiency, data organization, and the decisions programmers make when designing software.
Linear search has linear worst-case time complexity. Its maximum number of comparisons grows with the number of items.
Binary search has logarithmic worst-case time complexity when searching a sorted, efficiently indexed collection.
Binary search requires an appropriate ordering. Linear search can operate on sorted or unsorted collections.
What Is a Search Algorithm?
A search algorithm is a defined procedure for locating a particular value or record within a collection of information. The collection might contain numbers, words, objects, product identifiers, or other structured data.
The value being searched for is commonly called the target, search key, or query. Depending on the application, the algorithm may return the target’s position, the associated record, a Boolean result, or an indication that the item does not exist.
Consider a simple collection of student identification numbers:
An unsorted collection containing eight identification numbers.
If a program needs to determine whether the number 72 exists, it must examine the collection using an appropriate search procedure.
Different procedures can produce the same correct result while requiring dramatically different amounts of work. That difference becomes increasingly important as collections grow from a handful of values to millions of records.
Correctness
A search algorithm must correctly determine whether the requested item exists and return a result consistent with its defined behavior.
Efficiency
An efficient search algorithm minimizes unnecessary comparisons, memory usage, and processing work under the conditions in which it operates.
How Linear Search Works
Linear search, also known as sequential search, follows the simplest possible searching strategy. It starts at one end of a collection and examines each item individually.
When the current item matches the target, the algorithm returns the corresponding result. If it reaches the end without finding a match, it reports that the target is absent.
The method does not require the values to follow any particular order. It can search an alphabetical list, randomly arranged numbers, or records stored in the order they were created.
Start at the Beginning
Initialize the search at the first element of the collection.
Compare the Current Item
Determine whether the current element matches the target value.
Return the Matching Position
If the values match, return the current index or associated record.
Continue to the Next Item
If the values do not match, advance to the next element and repeat the comparison.
Report an Unsuccessful Search
If every element has been examined without a match, return a suitable not-found result.
The simplicity of linear search makes it particularly useful for small collections, temporary data, and situations where organizing information in advance would require unnecessary effort.
It also works naturally with data structures that support sequential traversal but do not provide efficient access to arbitrary positions.
Finding a Number Using Linear Search
Suppose an application contains the following eight numbers and needs to locate the value 31.
Target: 31
Four unsuccessful comparisons occur before the target is found at index 4.
| Comparison | Index | Current Value | Result |
|---|---|---|---|
| 1 | 0 | 12 | Not a match |
| 2 | 1 | 45 | Not a match |
| 3 | 2 | 18 | Not a match |
| 4 | 3 | 72 | Not a match |
| 5 | 4 | 31 | Target found |
The algorithm stops after five comparisons. Because most programming languages use zero-based indexing for arrays, the fifth element is located at index 4.
If the target had been the first value, only one comparison would have been necessary. If the target did not exist, the algorithm would need to examine all eight values.
Linear search does not require sorted data, but frequently requested items placed near the beginning of a collection may be found with fewer comparisons. The worst-case behavior remains linear.
How Binary Search Works
Binary search uses the ordering of a collection to eliminate large groups of values without examining them individually.
Imagine opening a dictionary to find a word beginning with the letter M. If the page you open contains words beginning with S, you immediately know that the desired word must appear earlier in the dictionary.
You do not need to examine every word between M and S. The alphabetical arrangement allows you to discard an entire section.
Binary search applies the same principle systematically. It examines the middle element of the current search range and uses the comparison result to determine which half could contain the target.
Target Is Smaller
When searching an ascending list, a target smaller than the middle value must occur in the remaining portion to the left, if it exists.
Target Is Larger
A target larger than the middle value must occur in the remaining portion to the right, if it exists.
Target Matches
When the middle element equals the target, the search can return that element’s index immediately.
Search Range Is Empty
If the lower boundary moves beyond the upper boundary, no possible matching elements remain.
The search range becomes approximately half as large after each unsuccessful comparison. This repeated reduction is responsible for binary search’s logarithmic growth in comparison count.
Calculating the middle index
mid = low + floor((high − low) / 2)The boundaries identify the current inclusive search range.
This midpoint calculation is also useful in programming languages with fixed-width integers because it avoids adding two potentially large index values directly.
Finding a Number Using Binary Search
Consider a sorted array containing eight numbers. The target is 42.
Step 1: Examine the Middle Element
The initial boundaries are index 0 and index 7. The lower middle index is 3, containing the value 21.
Because 42 is greater than 21, the first four elements can be eliminated.
Step 2: Search the Right Half
The remaining search range extends from index 4 to index 7. Its lower middle index is 5, containing 36.
Because 42 is greater than 36, the search continues with the last two elements.
Step 3: Locate the Target
The new midpoint is index 6. Its value is 42, so the search is complete.
Original collection size.
Binary search comparisons.
Linear search comparisons for the same target and array.
The difference may appear small in an eight-element collection, but the advantage of repeatedly eliminating half of the remaining possibilities becomes substantial when searching much larger arrays.
Experiment With Both Search Algorithms
The following simulator allows you to compare linear and binary search using the same sorted array. Enter a target number, select an algorithm, and advance through the comparisons individually.
Interactive Algorithm Simulator
Choose an algorithm and enter a target to begin.
Try searching for 4, 42, 57, and a missing value such as 100. Observe how the target’s position influences the number of comparisons performed by each algorithm.
Linear search may find an early element immediately, while binary search is particularly effective at limiting the maximum amount of work needed to search a large sorted array.
The Main Differences Between Linear and Binary Search
| Characteristic | Linear Search | Binary Search |
|---|---|---|
| Search strategy | Sequential examination | Repeatedly halves the search range |
| Sorted data required | No | Yes, according to a consistent ordering |
| Best-case time | O(1) | O(1) |
| Average-case time | O(n) under typical assumptions | O(log n) under typical assumptions |
| Worst-case time | O(n) | O(log n) |
| Iterative auxiliary space | O(1) | O(1) |
| Implementation difficulty | Very simple | Requires careful boundary management |
| Unsorted collections | Suitable | Requires ordering first |
| Sequential-access structures | Generally suitable | May lose its usual efficiency advantage |
| Large sorted arrays | Potentially inefficient | Generally efficient |
Neither algorithm is universally superior. Their usefulness depends on the structure of the information, the cost of preparing that information, and the number of searches the application needs to perform.
Understanding O(n) and O(log n)
Computer scientists use asymptotic notation to describe how an algorithm’s resource requirements grow as the input becomes larger.
Big O notation is commonly used to express an upper bound on growth. It does not directly measure execution time in seconds because actual performance depends on hardware, programming language, implementation details, and the cost of individual operations.
Linear Growth
In the worst case, linear search must examine every element. Doubling the collection size therefore doubles the maximum number of element checks.
Logarithmic Growth
Binary search eliminates approximately half of the remaining candidates after each unsuccessful comparison. Doubling the collection size generally adds only one additional comparison to its worst-case requirement.
Theoretical comparison counts for conventional iterative implementations, not measured execution times.
| Number of Items | Linear Search Maximum | Binary Search Maximum |
|---|---|---|
| 10 | 10 | 4 |
| 100 | 100 | 7 |
| 1,000 | 1,000 | 10 |
| 10,000 | 10,000 | 14 |
| 100,000 | 100,000 | 17 |
| 1,000,000 | 1,000,000 | 20 |
| 1,000,000,000 | 1,000,000,000 | 30 |
For a nonempty array containing n elements, a conventional binary search requires at most floor(logâ‚‚ n) + 1 midpoint examinations. This assumes constant-time indexed access and counts each examined element as one conceptual comparison.
Searching one million sorted values can therefore require only twenty midpoint examinations, compared with as many as one million sequential examinations using linear search.
Implementing Both Algorithms in Python
Python provides a readable way to demonstrate search algorithms. The following implementations return the zero-based index of a matching element or -1 when the target cannot be found.
Linear Search in Python
def linear_search(items, target):
for index, value in enumerate(items):
if value == target:
return index
return -1
numbers = [12, 45, 18, 72, 31, 56]
result = linear_search(numbers, 31)
print(result)
# Output: 4
The enumerate function provides both the index and the value during each iteration. When the target is found, the return statement ends the function immediately.
If no matching value exists, execution reaches the final return statement.
Binary Search in Python
def binary_search(items, target):
low = 0
high = len(items) - 1
while low <= high:
mid = low + (high - low) // 2
if items[mid] == target:
return mid
elif items[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
numbers = [4, 9, 15, 21, 28, 36, 42, 57]
result = binary_search(numbers, 42)
print(result)
# Output: 6
The variables low and high define the current search range. The midpoint is calculated using integer division, and each unsuccessful comparison removes the midpoint together with the portion that cannot contain the target.
The algorithm terminates when it finds a match or when the remaining range becomes empty.
The binary search implementation assumes that its input is sorted in ascending order. Passing an unsorted list can produce incorrect results even when the target is present.
Using Search Algorithms in JavaScript Applications
JavaScript applications frequently search collections of products, user records, messages, configuration values, and other information stored in arrays.
Linear Search in JavaScript
function linearSearch(items, target) {
for (let i = 0; i < items.length; i++) {
if (items[i] === target) {
return i;
}
}
return -1;
}
const numbers = [18, 7, 25, 42, 13];
console.log(linearSearch(numbers, 42));
// Output: 3
Binary Search in JavaScript
function binarySearch(items, target) {
let low = 0;
let high = items.length - 1;
while (low <= high) {
const mid = low +
Math.floor((high - low) / 2);
if (items[mid] === target) {
return mid;
}
if (items[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
const numbers = [7, 13, 18, 25, 42];
console.log(binarySearch(numbers, 42));
// Output: 4
JavaScript also provides built-in methods such as indexOf, find, and findIndex for common sequential searching tasks. These methods can be more convenient than writing a custom linear search implementation.
However, implementing the algorithm manually is useful for learning how comparisons, loops, and termination conditions work.
Why Binary Search Requires Sorted Information
Binary search depends on a logical relationship between the middle value and the values surrounding it. In an ascending array, every element before the midpoint is less than or equal to the middle value, and every element after it is greater than or equal to that value.
Without this ordering, the algorithm cannot safely eliminate either half.
An Unsorted Collection
The target is 42, and the lower middle element is 15. An ascending-order binary search would eliminate the left half because 42 is greater than 15.
However, the target is actually located in that eliminated portion. The search would incorrectly report that the value is absent.
Does Sorting Always Make Searching Faster?
Sorting a collection introduces its own computational cost. Many general-purpose comparison sorting algorithms require approximately O(n log n) time in typical or worst-case conditions, depending on the algorithm.
If an application needs to search an unsorted array only once, a linear search may require less total work than sorting the array and then performing binary search.
When the same collection is searched repeatedly, the initial sorting cost can be distributed across many searches.
One-Time Search
For a single lookup in an unsorted collection, sequential searching avoids the additional work of reorganizing the data.
Repeated Searches
Sorting once and performing many binary searches can substantially reduce total comparison work when the collection remains appropriately ordered.
Programmers must also consider whether sorting changes the original positions of records. If the original index is important, the application may need to preserve that information separately.
Handling Duplicate Values and Missing Items
Real-world collections frequently contain repeated values. A list of examination scores, product prices, or transaction amounts may include several identical entries.
Target: 20
The target appears at indices 2, 3, and 4.
A conventional linear search starting from the beginning returns the first matching position. A conventional binary search may return any matching position, depending on the midpoint sequence.
Finding the first or last occurrence requires a modified binary search that continues examining the relevant portion after discovering a match.
def first_occurrence(items, target):
low = 0
high = len(items) - 1
result = -1
while low <= high:
mid = low + (high - low) // 2
if items[mid] == target:
result = mid
high = mid - 1
elif items[mid] < target:
low = mid + 1
else:
high = mid - 1
return result
numbers = [5, 10, 20, 20, 20, 35, 48, 60]
print(first_occurrence(numbers, 20))
# Output: 2
This implementation remembers the most recently discovered matching index and continues searching toward the left. Its worst-case search complexity remains logarithmic.
What Happens When the Target Does Not Exist?
Linear search reaches the end of the collection. Binary search eventually produces an empty search range. Both can return a consistent not-found result, such as -1.
Applications should handle this result explicitly rather than assuming every requested value exists.
Where Search Algorithms Appear in Everyday Software
Searching is a building block of countless software systems. Although large production applications often use more specialized data structures and indexing techniques, the principles behind linear and binary search remain relevant.
Shopping Cart Applications
A small shopping cart may contain only a few products. Sequential searching can conveniently determine whether a particular product has already been added.
Sorted Product Identifiers
An application maintaining an ordered array of product identifiers can use binary search to locate a particular identifier efficiently.
Timestamp-Based Records
When records are stored in chronological order, modified binary searches can locate the boundaries of a requested time range.
Configuration Settings
Small collections of application settings can often be searched sequentially without introducing unnecessary complexity.
Educational Software
Algorithm visualization tools use both searching methods to teach loops, conditional statements, array indexing, and computational efficiency.
Ordered Thresholds
Binary search can locate the appropriate boundary in sorted collections of price thresholds, score ranges, or numerical limits.
Database engines and search platforms often use indexes, B-trees, hash tables, and inverted indexes rather than searching every stored record with these basic algorithms.
Nevertheless, understanding how sequential examination differs from ordered elimination helps explain why data organization plays such an important role in software performance.
How Data Storage Affects Search Performance
The usual logarithmic running time of binary search assumes that accessing the middle element is efficient. Arrays provide this capability because an element can generally be accessed directly using its index.
A linked list behaves differently. Reaching a particular position may require traversing several nodes from the beginning or another known location.
Arrays
Efficient indexed access makes sorted arrays well suited to binary search. The algorithm can examine a midpoint without visiting every preceding element.
Linked Lists
Sequential traversal makes linear search a natural choice. Binary search may still reduce value comparisons, but accessing midpoint positions can eliminate its logarithmic overall time advantage.
Iterative and Recursive Implementations
Binary search can be implemented using a loop or through recursive function calls. Both approaches can achieve logarithmic comparison complexity when operating on an appropriate array.
An iterative implementation generally requires constant auxiliary space because it maintains only a small number of variables. A straightforward recursive implementation uses additional call-stack space proportional to the number of recursive levels.
| Implementation | Worst-Case Time | Auxiliary Space |
|---|---|---|
| Iterative linear search | O(n) | O(1) |
| Iterative binary search | O(log n) | O(1) |
| Recursive binary search using index boundaries | O(log n) | O(log n) |
These space estimates exclude the original input collection and assume that the implementation does not create additional copies of the array.
Common Mistakes When Implementing Search Algorithms
Using Binary Search on Unsorted Data
This violates the fundamental assumption that allows the algorithm to eliminate half of its search range. Always establish or verify the required ordering before using binary search.
Incorrect Upper Boundary
For an inclusive zero-based search range, the initial upper boundary should be the collection length minus one. Using the collection length directly may cause an out-of-range access.
Failing to Remove the Midpoint
After an unsuccessful comparison, updating a boundary to mid rather than mid + 1 or mid – 1 can leave the search range unchanged and cause an infinite loop.
Using the Wrong Loop Condition
With inclusive boundaries, the condition low less than or equal to high ensures that the final remaining element is examined. Other boundary conventions require corresponding changes to the loop condition.
Assuming a Matching Index Is Always the First Occurrence
Standard binary search does not guarantee the first occurrence when duplicates exist. Use an appropriate boundary-search variation when that behavior is required.
Ignoring Empty Collections
Both algorithms should correctly handle empty arrays without attempting to access nonexistent elements.
Sorting Numbers Incorrectly in JavaScript
JavaScript’s default array sorting behavior compares string representations. For ordinary numeric ascending order, provide an appropriate numeric comparison function.
const numbers = [100, 5, 20, 3];
numbers.sort((a, b) => a - b);
console.log(numbers);
// Output: [3, 5, 20, 100]
The ordering used during sorting must be consistent with the comparisons performed by the search algorithm.
When Should You Choose Linear Search or Binary Search?
Selecting a search algorithm involves more than comparing theoretical time complexities. The best choice depends on how the information is stored, how frequently it changes, and what the application needs to retrieve.
Choose Linear Search When:
- The collection is small.
- The information is unsorted.
- Only occasional searches are required.
- Sequential traversal is inexpensive.
- Sorting would introduce unnecessary work.
- The first matching item in the original order is required.
Choose Binary Search When:
- The collection is already sorted.
- Efficient indexed access is available.
- The dataset contains many elements.
- Repeated searches are expected.
- Predictable worst-case comparison counts are important.
- Ordered boundaries or ranges need to be located.
Consider the Total Cost of the Operation
Imagine an application containing 100,000 unsorted records. If it needs to find one record and then discard the collection, sorting all records may be wasteful.
If the application maintains those records for months and performs thousands of lookups, an ordered structure or another suitable index may provide a much better long-term solution.
Frequent insertions and deletions also matter. Maintaining a sorted array can require moving elements when new records are inserted. An alternative structure, such as a balanced search tree or hash table, may be more appropriate depending on the required operations.
Optimize the complete workload rather than a single operation in isolation. Searching, sorting, updating, memory consumption, and implementation complexity all contribute to overall application performance.
Useful Test Cases for Search Algorithms
Testing helps confirm that a search implementation behaves correctly across ordinary and unusual inputs. A program that works for one example may still contain errors involving empty arrays, boundaries, or duplicate values.
| Input Collection | Target | Expected Result |
|---|---|---|
| [] | 10 | -1 |
| [10] | 10 | 0 |
| [10] | 20 | -1 |
| [2, 4, 6, 8] | 2 | 0 |
| [2, 4, 6, 8] | 8 | 3 |
| [2, 4, 6, 8] | 5 | -1 |
| [-8, -3, 0, 4] | -3 | 1 |
| [5, 10, 10, 20] | 10 | A matching index; first-occurrence search returns 1 |
Testing the first and last elements is especially important for binary search because these cases help expose incorrect boundary updates.
Missing values between existing elements should also be tested. They confirm that the algorithm terminates correctly when no matching position remains.
For larger automated test suites, developers can compare binary search results against a trusted sequential implementation, while accounting for differences in duplicate-handling behavior.
Frequently Asked Questions
What is the main difference between linear and binary search?
Linear search examines elements sequentially. Binary search uses the ordering of a collection to eliminate approximately half of the remaining candidates after each unsuccessful comparison.
Is binary search always faster than linear search?
No. Linear search can be faster for small collections, early matches, or one-time searches involving unsorted information. Binary search offers better worst-case comparison growth for appropriately sorted arrays.
Why does binary search require sorted data?
Sorting establishes the relationship between the midpoint and surrounding elements. Without that relationship, the algorithm cannot safely determine which portion of the collection to eliminate.
What is the worst-case time complexity of linear search?
O(n), because the algorithm may need to examine every element in the collection.
What is the worst-case time complexity of binary search?
O(log n), assuming the collection is sorted, midpoint access takes constant time, and individual comparisons have constant cost.
Can binary search work with descending order?
Yes. The comparison logic must be adjusted to match descending order rather than ascending order.
Can linear search find duplicate values?
Yes. A standard implementation returns the first matching value encountered. A modified implementation can collect every matching position.
Does binary search return the first duplicate?
Not necessarily. A conventional binary search returns a matching index. A specialized variation is required to guarantee the first or last occurrence.
How many comparisons are needed to binary search one million items?
A conventional binary search requires at most twenty midpoint examinations in a sorted array containing one million elements.
What does a return value of -1 mean?
In many search implementations, -1 indicates that no matching element was found. Other implementations may return null, None, or another defined result.
Can binary search be implemented recursively?
Yes. Each recursive call can search a smaller portion of the collection. A straightforward recursive implementation requires additional call-stack space.
Which search algorithm is easier for beginners?
Linear search is generally easier because it requires only a sequential loop and a matching condition. Binary search introduces midpoint calculations and boundary management.
Can binary search be used for words?
Yes. Words can be searched using binary search when they are arranged according to a consistent alphabetical or other comparison ordering.
Is binary search suitable for linked lists?
It is usually less attractive than it is for arrays because linked lists do not provide constant-time indexed access. The cost of locating midpoint elements can remove the usual logarithmic time advantage.
Does sorting count toward binary search complexity?
The binary search operation itself is logarithmic under its standard assumptions. However, if sorting is necessary before searching, its cost must be included when evaluating the complete task.
What happens when the search collection is empty?
A correctly implemented algorithm returns a not-found result without examining any elements.
Are hash tables faster than binary search?
Hash tables commonly provide expected constant-time exact-key lookups under suitable conditions. Binary search is useful for ordered information and range-related operations that ordinary hash tables do not naturally support.
Why should programmers learn both algorithms?
They demonstrate fundamental concepts involving loops, comparisons, data ordering, algorithm correctness, computational complexity, and the relationship between data structures and performance.
Efficient Searching Begins With Understanding Your Data
Linear search and binary search solve the same basic problem but approach it from different directions. Linear search relies on sequential examination, making it simple, flexible, and suitable for collections that do not follow a particular order.
Binary search takes advantage of organized information. By repeatedly eliminating approximately half of the remaining possibilities, it can locate values in large sorted arrays using remarkably few comparisons.
The difference between linear and logarithmic growth becomes increasingly significant as datasets expand. However, sorting costs, data structure limitations, update frequency, and duplicate-handling requirements must also be considered.
Learning these algorithms is valuable not simply because they appear in programming courses and technical interviews, but because they illustrate how thoughtful data organization can reduce unnecessary computational work.
The most effective search algorithm is the one that matches the structure of the information and the actual requirements of the application.

