saltandwater
saltandwater

Reputation: 841

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?

Upvotes: 2

Views: 428

Answers (3)

Anup
Anup

Reputation: 2434

The above answers are great just an addition if you want to know what is a linear search then it looks like this

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.Scanner;
class LargestElement
{
    public static void main(String[] args)
    {
        Scanner s = new Scanner(System.in);

        int ele= s.nextInt();
        int[] a = {1,2,6,4,5,4,3,1};

        for(int i = 0;i<a.length;i++)
        {
            if(a[i] ==ele)
                {
                        System.out.println("Element Found at : "+ (i+1)+" Position");
                }
        }

    }
}

Its your code that I edited it just linearly searches the array for a given value in this case I have taken it from console. There are variation on searching like binary search(used for sorted array) and there are many other searching algorithms but the most elementary one is linear search.

Upvotes: 0

vefthym
vefthym

Reputation: 7462

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.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

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.

Upvotes: 10

Related Questions