Professional Documents
Culture Documents
Linear Search
Linear Search
#include <stdio.h>
int main() {
int list[100];
int size;
int value;
printf("Enter the size of the list: ");
scanf("%d", &size);
for (int i = 0; i < size; i++) {
printf("Enter the value at index %d: ", i);
scanf("%d", &list[i]);
}
printf("Enter the value to search for: ");
scanf("%d", &value);
int index = linear_search(list, size, value);
if (index != -1) {
printf("The value was found at index %d\n", index);
} else {
printf("The value was not found\n");
}
return 0;
}
Linear_Search(a, n, val)
// 'a' is the given array, 'n' is the size of given array, 'val' is the
value to search
1. set pos = -1
2. set i = 1
3. repeat step 4 while i <= n
4. if a[i] == val set pos = i print pos go to step 6 [end of if]
5. set ii = i + 1 [end of loop]
6. if pos = -1 print "value is not present in the array " [end of if]
7. exit
Output:
● Simple to implement
● Efficient for small lists
● Can be used to search for any value
The time complexity of linear search is O(n), where n is the size of the list.
This is because the algorithm must iterate through the entire list to find the value.
In conclusion, linear search is a simple and efficient algorithm for searching for a
value in a small list. However, it is not as efficient for large lists.