If you want to practice data structure and algorithm programs, you can go through Java coding interview questions.
In this post, we will see about linear search in java.
Linear search is simple sequential search in which target element is searched one by one in the array. If element is found in the array then index will be returned else -1 will be returned.
Here is simple program for linear search.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
class LinearSearch { // This method returns index of element x in arr[] static int linearSearch(int arr[], int x) { for (int i = 0; i < arr.length; 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[]={16, 19, 21, 25, 3, 5, 8, 10}; int x = 5; int index = linearSearch(arr, x); if (index == -1) System.out.println("Element is not found in the array"); else System.out.println("Element found at position " + index); } } |
Output:
Element found at position 5
That’s all about linear search in java.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.