The multiple-item search algorithm is used to find all occurrences of a specific element in a list. Unlike single-item search algorithms, this approach keeps track of multiple occurrences of the target element and returns a list of their positions.
How It Works
- Start from the beginning of the list.
- Iterate through each element in the list.
- Compare the current element with the target value.
- If the current element equals the target value, record its position.
- Continue to the next element and repeat steps 3-4.
- After iterating through the entire list, return the list of recorded positions.
Example
Let's consider a list of integers and we want to find all occurrences of the number 23.
List: {12, 23, 45, 23, 56, 23, 89, 90}
- Start from the beginning: 12. Not the desired number.
- Move to the next element: 23. Match found, record position as 1.
- Move to the next element: 45. Not the desired number.
- Move to the next element: 23. Match found, record position as 3.
- Move to the next element: 56. Not the desired number.
- Move to the next element: 23. Match found, record position as 5.
- Move to the next element: 89. Not the desired number.
- Move to the next element: 90. Not the desired number.
- After iterating, return a list of positions: [1, 3, 5].
Example Code in C++
In the given example, the multipleItemSearch
function is used to find all occurrences of the number 23 in a list of integers. The result will be a vector containing the positions of all occurrences (positions start from 0).