Skip to content

fix: handle null and empty array in LinearSearch (issue #7340)#7347

Merged
DenizAltunkapan merged 1 commit intoTheAlgorithms:masterfrom
Senrian:fix/linear-search-null-handling
Mar 28, 2026
Merged

fix: handle null and empty array in LinearSearch (issue #7340)#7347
DenizAltunkapan merged 1 commit intoTheAlgorithms:masterfrom
Senrian:fix/linear-search-null-handling

Conversation

@Senrian
Copy link
Copy Markdown
Contributor

@Senrian Senrian commented Mar 28, 2026

Summary

Fixes issue #7340 - LinearSearch does not explicitly handle null or empty arrays, which can cause unexpected NullPointerExceptions or incorrect behavior.

Changes

  • Added null check at the start of find() method
  • Added empty array check (array.length == 0)
  • Returns -1 for null/empty input, consistent with BinarySearch behavior
  • Updated Javadoc to document the return value for null/empty cases

Behavior

Input Previous Behavior New Behavior
null array NPE Returns -1
Empty array [] Returns -1 (loop never runs) Returns -1 (explicit)
Valid array, found Returns index Unchanged
Valid array, not found Returns -1 Unchanged

This is consistent with how BinarySearch handles null/empty input.

Fixes #7340

@codecov-commenter
Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 50.00000% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 79.46%. Comparing base (cc75b5e) to head (53c08b6).

Files with missing lines Patch % Lines
.../java/com/thealgorithms/searches/LinearSearch.java 50.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff            @@
##             master    #7347   +/-   ##
=========================================
  Coverage     79.45%   79.46%           
- Complexity     7083     7084    +1     
=========================================
  Files           790      790           
  Lines         23164    23166    +2     
  Branches       4556     4557    +1     
=========================================
+ Hits          18405    18408    +3     
+ Misses         4022     4021    -1     
  Partials        737      737           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@DenizAltunkapan DenizAltunkapan merged commit 92d4702 into TheAlgorithms:master Mar 28, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Handle null and empty input in LinearSearch implementation

3 participants