Algorithm na bincike na binary hanya ce mafi inganci ta neman takamaiman abu a cikin jeri da aka jera. Ba kamar binciken layi ba, wanda ke bincika abubuwa a jere, binciken binary yana raba lissafin zuwa rabi kuma yana kwatanta abin da ake nufi da kashi na tsakiya. Ana maimaita wannan tsari har sai an sami abin da ake nufi ko kewayon bincike ya zama fanko.
Yadda Ake Aiki
- Fara da dukan jerawa jeri.
- Nemo tsakiya na kewayon bincike na yanzu.
- Kwatanta kashi na tsakiya tare da ƙimar manufa.
- Idan kashi na tsakiya yayi daidai da ƙimar manufa, binciken ya yi nasara.
- Idan kashi na tsakiya ya fi abin da aka sa gaba girma, bincika a rabi na hagu na kewayon.
- Idan kashi na tsakiya ya fi ƙanƙanta fiye da manufa, bincika a cikin dama rabin kewayon.
- Maimaita matakai 2-6 har sai an sami abin da ake nufi ko kewayon bincike ya zama fanko.
Misali
Bari mu yi la'akari da jeri jeri na lamba da kuma son nemo lamba 34 ta yin amfani da binary search.
Jerin Lissafi: {12, 23, 34, 45, 56, 67, 89, 90}
- Fara da jerin duka.
- Matsakaicin kashi: 56(matsayi na 4). Kwatanta da 34.
- 56 ya fi 34. Bincika a rabi na hagu.
- Sabon kashi na tsakiya: 23(matsayi na 1). Kwatanta da 34.
- 23 ya fi 34. Bincika a cikin rabin dama.
- Sabon kashi na tsakiya: 45(matsayi na 3). Kwatanta da 34.
- 45 ya fi 34. Bincika a rabi na hagu.
- Sabon kashi na tsakiya: 34(matsayi na 2). An samo manufa.
Misali Code a C++
#include <iostream>
#include <vector>
int binarySearch(const std::vector<int>& arr, int target) {
int left = 0;
int right = arr.size()- 1;
while(left <= right) {
int mid = left +(right- left) / 2;
if(arr[mid] == target) {
return mid;
} else if(arr[mid] < target) {
left = mid + 1;
} else {
right = mid- 1;
}
}
return -1;
}
int main() {
std::vector<int> numbers = {12, 23, 34, 45, 56, 67, 89, 90};
int target = 34;
int result = binarySearch(numbers, target);
if(result != -1) {
std::cout << "Element " << target << " found at position " << result << std::endl;
} else {
std::cout << "Element " << target << " not found in the array" << std::endl;
}
return 0;
}
A cikin misalin da aka bayar, binarySearch
ana amfani da aikin don nemo lamba 34 a cikin jerin jeri na lamba. Sakamakon zai zama matsayi na 34 a cikin jerin(matsayi sun fara daga 0) ko -1 idan ba a samo lambar ba.