Skip to content

Commit c5d53f4

Browse files
authored
Add Linear Search in C (#4399)
1 parent 405442a commit c5d53f4

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

archive/c/c/linear-search.c

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <string.h>
4+
#include <stdbool.h>
5+
6+
bool linear_search(int* arr, int size, int target) {
7+
for (int i = 0; i < size; i++) {
8+
if (arr[i] == target) {
9+
return true;
10+
}
11+
}
12+
return false;
13+
}
14+
15+
int* parse_array(char* input, int* size) {
16+
int* arr = NULL;
17+
*size = 0;
18+
char* token = strtok(input, ", ");
19+
while (token != NULL) {
20+
arr = realloc(arr, (*size + 1) * sizeof(int));
21+
arr[*size] = atoi(token);
22+
(*size)++;
23+
token = strtok(NULL, ", ");
24+
}
25+
return arr;
26+
}
27+
28+
int main(int argc, char* argv[]) {
29+
if (argc != 3) {
30+
printf("Usage: please provide a list of integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")\n");
31+
return 1;
32+
}
33+
34+
int size;
35+
int* arr = parse_array(argv[1], &size);
36+
int target = atoi(argv[2]);
37+
38+
if (size == 0) {
39+
printf("Usage: please provide a list of integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")\n");
40+
free(arr);
41+
return 1;
42+
}
43+
44+
bool result = linear_search(arr, size, target);
45+
printf("%s\n", result ? "true" : "false");
46+
47+
free(arr);
48+
return 0;
49+
}

0 commit comments

Comments
 (0)