How it works
Linear search inspects values in order until it finds a match or reaches the end. The function returns the first matching index and uses minus one to represent absence. Index zero is a valid success, so a caller must not treat it as false or missing. The algorithm works without sorting and has a worst-case number of comparisons proportional to the input length.
For a tiny list or a one-time search, that simplicity can be a good choice. If many lookups reuse the same collection, another structure may justify its preparation and memory costs. Choose based on the actual access pattern.
Search for the middle value, the last repeated value, and a value in an empty array. Count comparisons in each case and explain why the first match is returned.
A working example
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
Console.WriteLine(Find(new[] { 8, 3, 8 }, 8));
Console.WriteLine(Find(new[] { 8, 3, 8 }, 5));
int Find(int[] values, int target)
{
for (var i = 0; i < values.Length; i++) if (values[i] == target) return i;
return -1;
}
Expected output
0 -1
The missing sentinel must not overlap a valid array index.