-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLinear_search.c
42 lines (32 loc) · 967 Bytes
/
Linear_search.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <stdio.h>
#include <stdlib.h>
int linearSearch(short arr[], int size, short target) {
for (int i = 0; i < size; i++) {
if (arr[i] == target)
return i; // Target found at index i
}
return -1; // Target not found
}
int main() {
int size;
short *arr;
short target;
printf("Enter the size of the array: ");
scanf("%d", &size);
arr = (short*) malloc(size * sizeof(short));
printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++) {
printf("Element %d: ", i + 1);
scanf("%hd", &arr[i]);
}
printf("\nEnter the element to search: ");
scanf("%hd", &target);
int index = linearSearch(arr, size, target);
if (index != -1)
printf("\nElement %hd found at index %d.\n", target, index);
else
printf("\nElement %hd not found.\n", target);
free(arr);
return 0;
}
//complexity : O(n)