data-structures · beginner · ~15 min
Scan an array for a value.
Find the position of a value in an array by scanning it.
Implement int linear_search(const int *a, int n, int target) that returns the index of the first element equal to target, or -1 if it does not appear in the first n elements.
a: array of at least n ints (read-only, in any order).n: the number of elements.target: the value to search for.int: the index of the first match, or -1 if target is absent.
a={5,3,9,1}, target=9 -> 2
a={5,3,9,1}, target=5 -> 0 (first element)
a={5,3,9,1}, target=7 -> -1 (absent)
a: array of at least n ints (any order); n; target.
int: index of the first element equal to target, or -1.
Works on unsorted data.
int linear_search(const int *a, int n, int target) {
/* TODO */
return -1;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.