Walk an array once looking for a target value. Return the index of the first match, or -1 if none. The simplest possible search loop.

Algorithm

Canonical input arr = [4, 7, 1, 9, 3, 8] with target = 9 finishes after four compares; the matching index is 3.

Basic Implementation

basic.cs
using System;

class Program {
	static int LinearSearch(int[] arr, int target) {
		for (int i = 0; i < arr.Length; i++) {
			if (arr[i] == target) {
				return i;
			}
		}
		return -1;
	}

	static void Main() {
		int[] arr = new int[] { 4, 7, 1, 9, 3, 8 };
		int target = 9;
		int result = LinearSearch(arr, target);
		Console.WriteLine(result);
	}
}

Complexity

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

Implementation notes

  • C#: explicit for (int i = 0; i < arr.Length; i++) with an early return i; the moment arr[i] == target. LINQ's Array.FindIndex(arr, x => x == target) would hide the walk the lesson is teaching.
  • Method signature static int LinearSearch(int[] arr, int target) documents the array contract; the -1 sentinel mirrors the language-neutral spec rather than returning int?.
  • The replay shows the running index, the element being checked, and a match indicator on each frame.
early exit Return the index the moment `arr[i]` equals the target. Walking past it would defeat the point.
sentinel return A no-match walk falls off the loop and returns `-1`.