Data Structures and Algorithms • C# examples
Linear Search
Find a value in an unsorted collection with a simple single-pass algorithm.
Concept
Linear search checks candidates in sequence and stops at the first match. It works without sorted input and can be adapted to return the first index, all matches, or a predicate-based result. For unsorted data, it provides a dependable baseline against which more specialized structures can be compared.
How to approach it
Visit each position once; return when the equality or predicate condition succeeds.
Complexity
Best O(1), worst O(n), auxiliary space O(1).
C# example
static int FindIndex(int[] values, int target)
{
for (int i = 0; i < values.Length; i++)
if (values[i] == target) return i;
return -1;
}
Expected result or behavior
Returns the first matching index or -1 when the value is absent.
Practice exercise
Modify the method to return every matching index while preserving input order.
Key takeaway: Linear search is often the right choice for small or unsorted inputs.