Linear Search Java example. Easy solution. • IT Blog
IT Blog
Boris IT Expert

# Linear Search Java example. Easy solution.

Boris~November 12, 2020 /Search Algorithms

If you want to search an item in an array list, linear search (Java) most straightforward way. On the other hand, it is not the best solution. I would recommend using a binary search, but you can use a linear search if you forget how to implement it. It is better to show that something works and not elegant than elegant but not work correctly. Here, the basic idea is to loop through the array list and check if the current element is equal needed value.

## Linear search in Array List? The easy solution in Java.

Detailed implementation with the pictures and explanations. The most efficient solution below:

• We can set a variable to return as a result. The result will be an index of the needed element. If we did not find anything, we could return minus one. That means there is no such element in the array list;
``````//Value that we want to find
int searchedValue = 3;

int result = -1;``````
• Start the loop through an array;
``for (int i = 0; i < array.length; i++)``
• Check if the current element is equal to the searched value. If true, set the result variable to the index of the element and make a return;
`````` //Check if current item value is equals to searched value
if (array[i] == searchedValue) {
result = i;
}``````

Animation:

Full Schema:

Full code solution:

``````private void linearSearch() {
//Creating array of integers
int[] array = {4,2,3,1,5};

//Value that we want to find
int searchedValue = 3;

int result = -1;
for (int i = 0; i < array.length; i++) {
//Check if current item value is equals to searched value
if (array[i] == searchedValue) {
result = i;
}
}

Log.d("arrayList", "-> " + result);
}``````

In this article, I explained the principles of the linear search Java.

Full code and more examples in my facebook group.