Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to Create a Linear Search

DZone's Guide to

How to Create a Linear Search

Linear searches are a way to quickly find a target within a list. To create one, all you need is an algorithm and Java code.

· Big Data Zone
Free Resource

Effortlessly power IoT, predictive analytics, and machine learning applications with an elastic, resilient data infrastructure. Learn how with Mesosphere DC/OS.

Linear search, or sequential search, is a simple search algorithm for finding a target within a list. In this type of search, a sequential search will check every element within the list for a target value until a match is found. Otherwise, the search continues until the end of the list.

In the best case, the complexity of this algorithm is O(1) in the worst case, is O(n).

1. Algorithm

Linear search (array A, value x):

  1. Set i to 1.

  2. If i > n, then go to Step 7.

  3. If A[i] = x, then go to Step 6.

  4. Set i to i + 1.

  5. Go to Step 2.

  6. Return Element x found at index i and go to Step 8.

  7. Return -1.

  8. Exit.

2. Java Code

/**
* Simple Linear Search
* Complexity of the algorithm
* Best: O(1)
* Worst: O(n)
*/
public static int linearSearch(int[] array, int val){

    for (int i = 0; i < array.length; i++) {
        int num = array[i];
        if(val == num){
            return i;
        }
     }
     return -1;
}


Learn to design and build better data-rich applications with this free eBook from O’Reilly. Brought to you by Mesosphere DC/OS.

Topics:
linear search ,big data ,algorithms

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}