CKTIS / C
linear search — concept C23
Linear search examines elements in order and stops at the first match; for `n` elements it performs up to `n` comparisons, giving O(n) time and constant extra space. The result must distinguish index zero from no match, and the comparison must respect each element’s type and validity.
Version: C23
Syntax
linear searchLinear search examines elements in order and stops at the first match; for n elements it performs up to n comparisons, giving O(n) time and constant extra space. The result must distinguish index zero from no match, and the comparison must respect each element’s type and validity.
For an array, return the found index through an output parameter plus a separate bool, or use SIZE_MAX as a documented sentinel. If the first match is required, stop immediately; for all matches, pass results to a callback or a buffer with explicit capacity.
An empty array must finish without dereferencing, and the length cannot exceed the actual object. String search needs strcmp, not ==; structure equality must be defined by fields because padding prevents general use of memcmp.
Examples
#include <stdio.h>
int main(void) {
int values[] = {4, 7, 9}; size_t found = 3;
for (size_t i = 0; i < 3; ++i) if (values[i] == 7) { found = i; break; }
printf("%zu\n", found); return 0;
}
Result
1
Linear search examines elements in order and stops at the first match; for `n` elements it performs up to `n` comparisons, giving O(n) time and constant extra space. The result must distinguish index zero from no match, and the comparison must respect each element’s type and validity.