Searching Algorithms

Learn about the two most common searching algorithms, linear search and binary search.

Brute force: Linear search

This is the most simple searching algorithm.

How does linear search work?

We go through each element one by one. When the element we are searching for is found, we return its index. Here are some slides to make things clearer:

Press + to interact
canvasAnimation-image
1 / 5

Implementation

Linear search scans one item at a time and traverses the entire list to find the desired element.

using System;
class Program
{
public static int LinearSearch(int[] lst, int key)
{
if (lst.Length <= 0) // Sanity check
{
return -1;
}
for (int i = 0; i < lst.Length; i++)
{
if (lst[i] == key)
{
return i; // If found return index
}
}
return -1; // Return -1 otherwise
}
public static void Main(string[] args)
{
int[] lst = { 5, 4, 1, 0, 5, 95, 4, -100, 200, 0 };
int key = 95;
int index = LinearSearch(lst, key);
if (index != -1)
{
Console.WriteLine("Key: " + key + " is found at index: " + index);
}
else
{
Console.WriteLine(key + " is not found in the list.");
}
}
}

Performance of linear search

Linear search runs in O(n)O(n) ...