Java Program for Linear Search
Problem: Given an array arr[] of n elements, write a function to search a given element x in arr[].
Java
// Java code for linearly search x in arr[]. If x // is present then return its location, otherwise // return -1 class LinearSearch { // This function returns index of element x in arr[] static int search(int arr[], int n, int x) { for (int i = 0; i < n; i++) { // Return the index of the element if the element // is found if (arr[i] == x) return i; } // return -1 if the element is not found return -1; } public static void main(String[] args) { int[] arr = { 3, 4, 1, 7, 5 }; int n = arr.length; int x = 4; int index = search(arr, n, x); if (index == -1) System.out.println("Element is not present in the array"); else System.out.println("Element found at position " + index); } } |
chevron_right
filter_none
Output:
Element found at position 1
The time complexity of the above algorithm is O(n).
Please refer complete article on Linear Search for more details!
Recommended Posts:
- C/C++ Program for Linear Search
- Java Program for Anagram Substring Search (Or Search for all permutations)
- Linear Search vs Binary Search
- Linear Search
- Sentinel Linear Search
- Linear search using Multi-threading
- Java Program for Binary Search (Recursive and Iterative)
- C Program for Binary Search (Recursive and Iterative)
- Recursive program to linearly search an element in a given array
- Search a string in Matrix Using Split function in Java
- Repeatedly search an element by doubling it after every successful search
- Search equal, bigger or smaller in a sorted array in Java
- Why is Binary Search preferred over Ternary Search?
- Java Program for Program to calculate area of a Tetrahedron
- Java Program for Program to find area of a circle

