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:

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

//Result of the algorithm / if not found -1
        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;
            }

Animation:

Full Schema:

linear search java

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;

        //Result of the algorithm / if not found -1
        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.

Useful links:

Leave Any Questions Related To This Article Below!