Algorithms
Linear Search
Linear search checks each element until it finds the target or reaches the end.
target
The target value is compared with each array element.
found index
The result stays `-1` until a matching element is found.
Linear Search
linear_search.c
Replay: real traced execution (multi-file project)
#include <stdio.h>
int main(void) {
int values[5] = {4, 7, 9, 12, 15};
int target = 12;
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 = 6;
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 = 7;
int found = -1;
for (int i = 0; i < 5; i++) {
if (values[i] == target) {
found = i;
break;
}
}
printf("found=%d\n", found);
return 0;
}
values ← ⟨addr A⟩, target ← 12, found ← -1
3int main(void) {4 int values→ ⟨addr A⟩[5] = {4, 7, 9, 12, 15};5 int target→ 12 = 12; //@target=7, 66 int found→ -1 = -1;for (int i = 0; i < 5; i++)
pass 1 of 48for (int i0 = 0; i < 5; i++) {9 if (values[i] == target) {All 4 passes — pass 1 is the card above pass ivalues[i]targetfound1 0 — — — 2 1 — — — 3 2 — — — 4 3 12 12 -1 → 3 found ← 3
8for (int i = 0; i < 5; i++) {9 if (values[i]12 == target12) {10 found→ 3 = i3;11 break;12 }printf("found=%d ", found);
15 printf("found=%d\n", found3);16 return 0;17}outputfound=3
values ← ⟨addr A⟩, target ← 6, found ← -1
3int main(void) {4 int values→ ⟨addr A⟩[5] = {4, 7, 9, 12, 15};5 int target→ 6 = 6;6 int found→ -1 = -1;for (int i = 0; i < 5; i++)
pass 1 of 58for (int i0 = 0; i < 5; i++) {9 if (values[i] == target) {All 5 passes — pass 1 is the card above pass i1 0 2 1 3 2 4 3 5 4 printf("found=%d ", found);
15 printf("found=%d\n", found-1);16 return 0;17}outputfound=-1
values ← ⟨addr A⟩, target ← 7, found ← -1
3int main(void) {4 int values→ ⟨addr A⟩[5] = {4, 7, 9, 12, 15};5 int target→ 7 = 7;6 int found→ -1 = -1;for (int i = 0; i < 5; i++)
pass 1 of 28for (int i0 = 0; i < 5; i++) {9 if (values[i] == target) {for (int i = 0; i < 5; i++)
pass 2 of 28for (int i1 = 0; i < 5; i++) {9 if (values[i] == target) {found ← 1
8for (int i = 0; i < 5; i++) {9 if (values[i]7 == target7) {10 found→ 1 = i1;11 break;12 }printf("found=%d ", found);
15 printf("found=%d\n", found1);16 return 0;17}outputfound=1