Linear search is a simple searching algorithm that works by sequentially comparing each element of an array to the target value. The algorithm starts at the beginning of the array and compares the target value to the first element. If the target value is found, the algorithm returns the index of the element. If the target value is not found, the algorithm moves on to the next element and repeats the comparison. This process continues until the end of the array is reached. If the target value is not found in the array, the algorithm returns -1.
Here is the pseudocode for linear search:
procedure linear_search(array, target)
for i from 0 to n - 1
if array[i] == target
return i
return -1
Here is the C code for linear search:
int linear_search(int array[], int size, int target) {
for (int i = 0; i < size; i++) {
if (array[i] == target) {
return i;
}
}
return -1;
}
To use the linear search algorithm, you would first need to create an array of integers. Then, you would call the linear_search function, passing in the array, the size of the array, and the target value as parameters. The function will return the index of the element in the array if the target value is found, or -1 if the target value is not found.
Here is an example of how to use the linear search algorithm in C:
int main() {
int array[] = {10, 5, 2, 7, 1, 8};
int size = sizeof(array) / sizeof(array[0]);
int target = 7;
int index = linear_search(array, size, target);
if (index == -1) {
printf("The target value was not found.");
} else {
printf("The target value was found at index %d.", index);
}
return 0;
}
This code will print the following output:
The target value was found at index 3.
As you can see, the linear search algorithm has found the target value at index 3 in the array.
Linear search is a simple and easy-to-understand algorithm. However, it is not very efficient. It has a worst-case time complexity of O(n), where n is the size of the array. This means that the time it takes to find the target value grows linearly with the size of the array.
There are more efficient searching algorithms available, such as binary search. However, linear search is a good algorithm to learn for beginners because it is easy to understand and implement.