Algoritma telusuran macem-macem item digunakake kanggo nemokake kabeh kedadeyan saka unsur tartamtu ing dhaptar. Ora kaya algoritma panelusuran item siji, pendekatan iki nglacak pirang-pirang kedadeyan saka unsur target lan ngasilake dhaptar posisi.
Cara Kerjane
- Miwiti saka wiwitan dhaptar.
- Ulangi saben unsur ing dhaptar.
- Bandhingake unsur saiki karo nilai target.
- Yen unsur saiki padha karo nilai target, cathet posisine.
- Terusake menyang unsur sabanjure lan baleni langkah 3-4.
- Sawise ngulang kabeh dhaptar, bali dhaptar posisi sing direkam.
Tuladha
Ayo nimbang dhaptar integer lan kita pengin nemokake kabeh kedadeyan nomer 23.
Dhaptar: {12, 23, 45, 23, 56, 23, 89, 90}
- Mulai saka awal: 12. Ora nomer sing dikarepake.
- Pindhah menyang unsur sabanjure: 23. Cocokake ditemokake, rekam posisi minangka 1.
- Pindhah menyang unsur sabanjure: 45. Ora nomer sing dikarepake.
- Pindhah menyang unsur sabanjure: 23. Cocokake ditemokake, rekam posisi minangka 3.
- Pindhah menyang unsur sabanjure: 56. Ora nomer sing dikarepake.
- Pindhah menyang unsur sabanjure: 23. Cocokake ditemokake, rekam posisi minangka 5.
- Pindhah menyang unsur sabanjure: 89. Ora nomer sing dikarepake.
- Pindhah menyang unsur sabanjure: 90. Ora nomer sing dikarepake.
- Sawise iterasi, bali dhaptar posisi: [1, 3, 5].
Tuladha Kode ing C++
#include <iostream>
#include <vector>
std::vector<int> multipleItemSearch(const std::vector<int>& arr, int target) {
std::vector<int> positions;
for(int i = 0; i < arr.size(); ++i) {
if(arr[i] == target) {
positions.push_back(i);
}
}
return positions;
}
int main() {
std::vector<int> numbers = {12, 23, 45, 23, 56, 23, 89, 90};
int target = 23;
std::vector<int> result = multipleItemSearch(numbers, target);
std::cout << "Occurrences of " << target << " found at positions: ";
for(int pos: result) {
std::cout << pos << ";
}
std::cout << std::endl;
return 0;
}
Ing conto sing diwenehake, multipleItemSearch
fungsi kasebut digunakake kanggo nemokake kabeh kedadeyan nomer 23 ing dhaptar integer. Asil bakal dadi vektor sing ngemot posisi kabeh kedadeyan(posisi diwiwiti saka 0).