Implement Linear Search using Java
Technology and generation are growing up together, and the younger generation users are somewhat connected with tech and the internet all the time. Not to mention, today the whole world in this time of crisis is working over the internet. But to make these technologies, softwares, etc a software developer must have excellent problem-solving skills. In this world where the internet is the new fuel, one needs to be pretty sharp. And by sharp, for software developers, it means knowing how to automate real-world problems using computer programs. Data structures help a lot in this journey of logic building. So today we’re going to write a simple data structure program to Implement Linear Search using Java.
What is A Linear Search?
Linear search is the most basic searching for all algorithms in data structures. Also, it’s pretty easy to understand. But due to its slow searching speed, the Linear search algorithm is pretty rare to see in practical usage.
In a list/array to use Linear search one has to traverse the list/array at a time. Due to this reason, the time complexity of this algorithm is higher.
What’s The Approach?
- In an input array, we’ll start with the leftmost element index. We’ll traverse the array one by one comparing the number to be found (
x
) with the element present in the array.
- If
X
matches with the array element then we’ll print the index. Otherwise, we’llreturn -1.
Also Read: Multiply Integers without Multiplication Arithmetic Operator in Java
Java Program To Implement Linear Search
Input:
2, 3, 4, 10, 40
Output:
Element is present at index 3
// Java code for Linear searching class TechDecodeTutorials { public static int search(int arr[], int x) { int n = arr.length; for (int i = 0; i < n; i++) { if (arr[i] == x) return i; } return -1; } // Driver code public static void main(String args[]) { int arr[] = { 2, 3, 4, 10, 40 }; int x = 10; // Function call int result = search(arr, x); if (result == -1) System.out.print( "Element is not present in array"); else System.out.print("Element is present at index " + result); } }