Linear Search in Java

In the realm of computer science and programming, searching is a fundamental operation. It involves finding a specific element within a collection of elements. One simple yet essential searching algorithm is the Linear Search.

What is Searching?

Searching is the process of finding a particular item in a collection of items. It is a common operation in many applications, ranging from databases to everyday programming tasks.

Linear Search is a straightforward searching algorithm that traverses a list sequentially to find a target element. It iterates through each element until a match is found or the entire list is searched. While not the most efficient algorithm for large datasets, it is easy to implement and applicable in various scenarios.

linear search algorithm
linear search

Linear Search Algorithm

  1. Start at the beginning of the list.

  2. Compare the target element with the current element.

  3. If a match is found, return the index of the current element.

  4. If the end of the list is reached without finding a match, return -1 to indicate that the element is not present.

Pseudocode

Let's delve into a basic implementation of Linear Search in Java:

Time Complexity

The time complexity of the Linear Search algorithm is O(n), where 'n' is the number of elements in the list or array. It performs a constant amount of work for each element in the worst case.

🎯 Questions

Q1: Search in String

Write a Java function to perform a linear search for a specific character in a given string.

Q2: Search in Range

Modify the linear search code to search for an element within a specified range in an array.

Q3: Minimum Number

Implement a linear search to find the minimum number in an array.

Q4: Search in 2D Arrays

Extend the linear search algorithm to work with a two-dimensional array.

Q5: Even Digits

Question link: https://leetcode.com/problems/find-numbers-with-even-number-of-digits/

Q6: Max Wealth

Question link: https://leetcode.com/problems/richest-customer-wealth/

Feel free to explore and experiment with these questions to deepen your understanding of linear search in Java. Happy coding!

Last updated

Was this helpful?