Alan Zhan Blog

Live for nothing, or die for something

When checking whether an element exists, what is the most common approach? The answer is a for or while loop. Congratulations — you’ve already learned Linear Search!

Concept

Linear Search: This algorithm visits every element to check where the element is located in the array. If the element is not found, it returns -1.

Complexity

  • Time complexity: O(n)
  • Space complexity: O(1)

Examples

Go

package main

import "fmt"

func linearSearch(list []int, target int) int {
    for i := 0; i < len(list); i++ {
        if list[i] == target {
            return i
        }
    }
    return -1
}

func main() {
    fmt.Println(linearSearch([]int{1, 2, 3, 4, 5}, 3)) // 2
    fmt.Println(linearSearch([]int{1, 2, 3, 4, 5}, 6)) // -1
}

C#

class Algorithm
{
    public static int linearSearch(int[] list, int target)
    {
        for (var i = 0; i < list.Length; i++)
        {
            if (list[i] == target)
            {
                return i;
            }
        }

        return -1;
    }

    public static void Main(String[] args)
    {
        Console.WriteLine(linearSearch(new int[] {1, 2, 3, 4, 5}, 3)); // 2
        Console.WriteLine(linearSearch(new int[] {1, 2, 3, 4, 5}, 6)); // -1
    }
}

Feel free to leave a comment on my blog. Your feedback motivates me to keep writing. Thank you for reading, and let’s grow together to become better versions of ourselves.