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.
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.