Skip to content

Commit 521d027

Browse files
Merge pull request matthewsamuel95#786 from hirakJS/linear_search
Add Linear Search implementation in C
2 parents 29b3d33 + c4257b1 commit 521d027

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Search/LinearSearch/C/linear_search.c

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#include <stdio.h>
2+
3+
int search(int arr[], int n, int key)
4+
{
5+
int i;
6+
for (i = 0; i < n; i++)
7+
{
8+
if (arr[i] == key)
9+
break;
10+
}
11+
12+
return (i == n) ? -1 : i;
13+
}
14+
15+
int main()
16+
{
17+
int arr[] = {4, 10, 8, 25, 13, 89, 45, 12, 78, 11};
18+
int key = 78;
19+
int n = sizeof(arr) / sizeof(int);
20+
21+
int res = search(arr, n, key);
22+
23+
if (res == -1)
24+
printf("%d is not found!\n", key);
25+
else
26+
printf("%d is found at position %d.\n", key, res + 1);
27+
28+
return 0;
29+
}

0 commit comments

Comments
 (0)