Linear search is a simple way to find something in a list. It looks at each item one by one until it finds what you're looking for, or it finishes looking through the list.
Let’s look at an example:
Imagine we have a list of numbers:
[ \text{array} = [3, 5, 2, 8, 6] ]
Now, let’s say we want to find the number:
[ \text{target} = 8 ]
Here’s how the search works:
Start at the first number (this is called index 0):
3
(not the number we want).Move to the next number (index 1):
5
(not the number we want).Move to the next number (index 2):
2
(still not the number we want).Move to the next number (index 3):
8
(yes! We found it!).Understanding the Search:
In this example, the linear search checked 4 numbers before finding the target.
The time it takes to search grows with the size of the list. This is called time complexity, and for linear search, it's , where is the number of items in the list.
The worst case happens if the number we want is at the end of the list or not there at all. In that case, we'd have to check all numbers.
For a list with 1000 items, the most comparisons we could make would be 1000.
This method is simple but can be slow when dealing with large lists. There are faster ways to search, like binary search, but that only works with lists that are sorted and is much quicker at time.
Linear search is a simple way to find something in a list. It looks at each item one by one until it finds what you're looking for, or it finishes looking through the list.
Let’s look at an example:
Imagine we have a list of numbers:
[ \text{array} = [3, 5, 2, 8, 6] ]
Now, let’s say we want to find the number:
[ \text{target} = 8 ]
Here’s how the search works:
Start at the first number (this is called index 0):
3
(not the number we want).Move to the next number (index 1):
5
(not the number we want).Move to the next number (index 2):
2
(still not the number we want).Move to the next number (index 3):
8
(yes! We found it!).Understanding the Search:
In this example, the linear search checked 4 numbers before finding the target.
The time it takes to search grows with the size of the list. This is called time complexity, and for linear search, it's , where is the number of items in the list.
The worst case happens if the number we want is at the end of the list or not there at all. In that case, we'd have to check all numbers.
For a list with 1000 items, the most comparisons we could make would be 1000.
This method is simple but can be slow when dealing with large lists. There are faster ways to search, like binary search, but that only works with lists that are sorted and is much quicker at time.