Skip to content

Commit 50f6ed9

Browse files
committed
Same here
1 parent 4b0790d commit 50f6ed9

1 file changed

Lines changed: 34 additions & 21 deletions

File tree

archive/c/c/linear-search.c

Lines changed: 34 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,55 @@
1+
#include <stdbool.h>
12
#include <stdio.h>
23
#include <stdlib.h>
4+
#include <string.h>
35

4-
int josephus(int n, int k)
6+
bool linear_search(int *arr, int size, int target)
57
{
6-
if (n == 1)
7-
return 1;
8-
else
9-
return (josephus(n - 1, k) + k - 1) % n + 1;
8+
for (int i = 0; i < size; i++)
9+
if (arr[i] == target)
10+
return true;
11+
return false;
1012
}
1113

12-
int main(int argc, char *argv[])
14+
int *parse_array(char *input, int *size)
1315
{
14-
if (argc != 3)
16+
int *arr = NULL;
17+
*size = 0;
18+
char *token = strtok(input, ", ");
19+
while (token != NULL)
1520
{
16-
printf("Usage: please input the total number of people and number of "
17-
"people to skip.\n");
18-
return 1;
21+
arr = realloc(arr, (*size + 1) * sizeof(int));
22+
arr[*size] = atoi(token);
23+
(*size)++;
24+
token = strtok(NULL, ", ");
1925
}
26+
return arr;
27+
}
2028

21-
char *endptr;
22-
int n = strtol(argv[1], &endptr, 10);
23-
if (*endptr != '\0' || n <= 0)
29+
int main(int argc, char *argv[])
30+
{
31+
if (argc != 3)
2432
{
25-
printf("Usage: please input the total number of people and number of "
26-
"people to skip.\n");
33+
printf("Usage: please provide a list of integers (\"1, 4, 5, 11, 12\") "
34+
"and the integer to find (\"11\")\n");
2735
return 1;
2836
}
2937

30-
int k = strtol(argv[2], &endptr, 10);
31-
if (*endptr != '\0' || k <= 0)
38+
int size;
39+
int *arr = parse_array(argv[1], &size);
40+
int target = atoi(argv[2]);
41+
42+
if (size == 0)
3243
{
33-
printf("Usage: please input the total number of people and number of "
34-
"people to skip.\n");
44+
printf("Usage: please provide a list of integers (\"1, 4, 5, 11, 12\") "
45+
"and the integer to find (\"11\")\n");
46+
free(arr);
3547
return 1;
3648
}
3749

38-
int result = josephus(n, k);
39-
printf("%d\n", result);
50+
bool result = linear_search(arr, size, target);
51+
printf("%s\n", result ? "true" : "false");
4052

53+
free(arr);
4154
return 0;
4255
}

0 commit comments

Comments
 (0)