Algorithms
Linear Search
Linear search checks each element until it finds the target or reaches the end.
Linear Search
linear_search.c
#include <stdio.h>
int main(void) {
int values[5] = {4, 7, 9, 12, 15};
int target = ;
int found = -1;
for (int i = 0; i < 5; i++) {
if (values[i] == target) {
found = i;
break;
}
}
printf("found=%d\n", found);
return 0;
}
#include <stdio.h>
int main(void) {
int values[5] = {4, 7, 9, 12, 15};
int target = ;
int found = -1;
for (int i = 0; i < 5; i++) {
if (values[i] == target) {
found = i;
break;
}
}
printf("found=%d\n", found);
return 0;
}
#include <stdio.h>
int main(void) {
int values[5] = {4, 7, 9, 12, 15};
int target = ;
int found = -1;
for (int i = 0; i < 5; i++) {
if (values[i] == target) {
found = i;
break;
}
}
printf("found=%d\n", found);
return 0;
}
target
The target value is compared with each array element.
found index
The result stays `-1` until a matching element is found.