Sequential search, also called linear search, checks the elements one by one from the start until it finds the value or runs out of elements. It needs no preparation and works on unsorted data, which is its whole appeal. The cost is O(n): searching a million elements can take a million comparisons.
Use the built-in methods
For most code, the framework already has what you need:
int[] numbers = [28, 4, 106, 11, 20, 1, 96];
int index = Array.IndexOf(numbers, 20);
Console.WriteLine(index); // 4
int notFound = Array.IndexOf(numbers, 50);
Console.WriteLine(notFound); // -1
// Search by a condition instead of a value.
int firstLarge = Array.FindIndex(numbers, n => n > 50);
Console.WriteLine(firstLarge); // 2
List<T> has the same pair as instance methods: IndexOf and FindIndex. If you only need a yes or no, Contains reads better. For spans there is numbers.AsSpan().IndexOf(20), and for primitive types such as int, byte and char it is vectorized: it compares several elements per CPU instruction, which no hand-written loop in plain C# will match.
A generic implementation
Writing it yourself is short:
public static class Search
{
public static int SequentialSearch<T>(T[] items, T value)
=> SequentialSearch((ReadOnlySpan<T>)items, value);
public static int SequentialSearch<T>(ReadOnlySpan<T> items, T value)
{
var comparer = EqualityComparer<T>.Default;
for (int i = 0; i < items.Length; i++)
{
if (comparer.Equals(items[i], value))
return i;
}
return -1;
}
}
int[] numbers = [28, 4, 106, 11, 20, 1, 96];
Console.WriteLine(Search.SequentialSearch(numbers, 20)); // 4
string?[] names = ["Ann", null, "Bob"];
Console.WriteLine(Search.SequentialSearch(names, "Bob")); // 2
EqualityComparer<T>.Default is what Array.IndexOf uses as well. It calls IEquatable<T>.Equals when the type implements it, which avoids boxing for structs, and it handles null on both sides. Calling items[i].Equals(value) directly would throw a NullReferenceException on the null in the second example.
For strings, think about what “equal” means. The default comparer is ordinal and case-sensitive. For a case-insensitive search, use a predicate, Array.FindIndex(names, n => string.Equals(n, "bob", StringComparison.OrdinalIgnoreCase)), or give the generic method an IEqualityComparer<T> parameter.
The sentinel trick, and why the old version was broken
The earlier version of this post used a “sentinel”: it wrote the search value into the last slot of the array so the loop would always find it and could skip the i < length check. That code had two real bugs:
- It overwrote the last element of the caller’s array and never restored it, so searching corrupted the data.
- Because the last slot was always the sentinel, a value that really was in the last position was reported as not found.
The correct form saves the last element, places the sentinel, searches, then restores the element and checks it separately. In C# it is not worth it. The JIT removes the bounds check from a for (int i = 0; i < span.Length; i++) loop, so the loop already does one comparison per element plus a cheap counter check, and the sentinel version cannot work on read-only data or spans at all. Use the plain loop or, better, IndexOf.
Complexity
| Case | Comparisons |
|---|---|
| Best (first element) | 1 |
| Average (value present) | about n / 2 |
| Worst (last element or missing) | n |
Extra space is O(1).
When to use something else
A linear search is the right tool for small collections, for data you search only once, and for conditions that cannot be indexed (n => n.Name.Contains("x")). If you search the same data many times, change the data structure instead:
- Sort it once and use binary search, O(log n) per lookup.
- Put it in a
HashSet<T>orDictionary<TKey, TValue>, O(1) per lookup on average.
For fewer than a few dozen elements, a linear scan of an array is often faster than either, because it walks memory in order and has no hashing or branching overhead. Measure before you optimize.
1 thought on “Sequential (Linear) Search in C#: IndexOf and a Generic Version”