Linear Search in Array
First, What is Linear Search?
Linear search, also known as sequential search, is a method for finding a particular value in a list by checking each element in the list one by one until the desired element is found or the list ends. This search method is used on a collection of items where the items are stored in a random order. It does not require the list to be sorted beforehand, making it straightforward but not always the most efficient.
How Does Linear Search Work?
The process of linear search is simple:
- Start from the first element of the array.
- Compare the current element with the value you're searching for.
- If the value matches, return the index of this element.
- If the value does not match, move to the next element.
- If you reach the end of the array and have not found the value, the search is unsuccessful.
Code Example
linear search in array
/**
* @brief Find the index of target, return -1 if target not found
*
* @param arr
* @param size
* @param target
* @return int
*/
int search(const int* arr, const int size, const int target) {
for (auto i = 0; i < size; i++) {
if (arr[i] == target) {
return i;
} else {
return -1
}
}
}