Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is this algorithm called linear search?

Say, I am trying to find the largest element in an array, and I write some code as follows.

public class LargestElement
{
    public static void main(String[] args)
    {
        int[] a = {1,2,6,4,5,4,3,1};

        int max = a[0];
        for(int i = 1;i<a.length;i++)
        {
            if(a[i] > max)
                max = a[i];
        }

        System.out.println(max);
    }
}

Is this called Linear Search?

like image 428
saltandwater Avatar asked Aug 03 '26 01:08

saltandwater


2 Answers

Since the algorithm is finding the highest value in a collection, it is called a linear selection algorithm, not a linear search algorithm. This is different from a search algorithm, which looks for a specific value.

like image 57
Sergey Kalinichenko Avatar answered Aug 04 '26 14:08

Sergey Kalinichenko


No, it is not a linear search, as you are not looking for an element in this array, but for the maximum value in this array. It always checks all the elements of the array, while a linear-search algorithm terminates when a specific value (the one you are searching) is found. However, the complexity of this algorithm is indeed linear (more details on complexity here).

Quoting the description of the "linear-search" tag that is also included in the question:

Linear search or sequential search is a method for finding a particular value in a list, that consists of checking every one of its elements, one at a time and in sequence, until the desired one is found. Linear search is the simplest search algorithm. Its worst case cost is proportional to the number of elements in the list.

like image 20
vefthym Avatar answered Aug 04 '26 16:08

vefthym



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!