data-structures · beginner · ~15 min

Linear search

Scan an array for a value.

Challenge

Find the position of a value in an array by scanning it.

Task

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.

Input

  • a: array of at least n ints (read-only, in any order).
  • n: the number of elements.
  • target: the value to search for.

Output

int: the index of the first match, or -1 if target is absent.

Example

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)

Edge cases

  • An absent target returns -1.
  • Returns the index of the first match if duplicates exist.

Input format

a: array of at least n ints (any order); n; target.

Output format

int: index of the first element equal to target, or -1.

Constraints

Works on unsorted data.

Starter code

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.