You are on page 1of 2

Linear Search Code:

#include <stdio.h>

int linear_search(int *list, int size, int value) {


int pos = -1;
for (int i = 0; i < size; i++) {
if (list[i] == value) {
pos = i;
break;
}
}
return pos;
}

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;
}

Here is the algorithm for linear search:

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:

Enter the size of the list: 5


Enter the value at index 0: 10
Enter the value at index 1: 20
Enter the value at index 2: 30
Enter the value at index 3: 40
Enter the value at index 4: 50
Enter the value to search for: 30
The value was found at index 2

Advantages of linear search:

● Simple to implement
● Efficient for small lists
● Can be used to search for any value

Disadvantages of linear search:

● Inefficient for large lists


● Can take a long time to find the value if it is not at the beginning of the list

Time complexity analysis:

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.

You might also like