Algorithm din Binciken Binary hanya ce mai inganci don nemo takamaiman ƙima a cikin tsararrun tsararru. Wannan hanya tana raba tsararrun zuwa ƙananan sassa kuma tana ci gaba da kwatanta ƙimar a tsakiyar kewayon bincike tare da ƙimar manufa. Idan ƙimar ta yi daidai, ana samun ƙimar da ake so; in ba haka ba, algorithm ya ci gaba da ƙaddamar da kewayon bincike kuma yana maimaita tsari har sai an sami ƙimar ko ba a bar ƙarin abubuwa don bincika ba.
Matakai:
- Fara kewayon bincike: Fara da zaɓar kewayon bincike daga matsayi na farko
left
zuwa matsayi na ƙarsheright
na tsararru. - Nemo tsakiyar tsakiya: Ƙididdige wurin tsakiya ta hanyar matsakaici
left
da matsayi na dama; wannan shine tsakiyar zangon bincike. - Kwatanta dabi'u: Kwatanta ƙima a tsakiya tare da ƙimar manufa.
- Sarrafa sakamakon kwatance: Idan ƙima a tsakiya ta yi daidai da ƙimar manufa, mayar da wannan matsayi. Idan darajar a tsakiya ta kasa da ƙimar manufa, sabunta matsayin hagu zuwa tsakiya + 1 don bincika rabin dama. Idan darajar a tsakiyar tsakiya ta fi darajar manufa, sabunta matsayi na dama zuwa tsakiya- 1 don bincika rabi na hagu.
- Maimaita: Maimaita matakai 2 zuwa 4 har sai an sami ƙimar ko babu ƙarin abubuwan da za a bincika
left > right
.
Abũbuwan amfãni da rashin amfani
Amfani:
- Ingantacciyar aiki: Tsararren lokaci na algorithm shine O(log n), yana mai da shi inganci sosai don sarrafa manyan bayanai.
- Mai tasiri ga manyan bayanan bayanai: Binciken Binary yana da tasiri wajen rage adadin abubuwan da za a bincika da sauri don manyan bayanan bayanai.
Rashin hasara:
- Ana amfani da shi kawai don tsararrun tsararraki: Algorithm ɗin yana aiki ne kawai akan tsararrun tsararru.
- Adadin matakan matakai: Adadin matakan da ake buƙata don nemo ƙimar ya dogara da matsayinsa a cikin tsararru, kuma yana iya ɗaukar matakai da yawa don ƙimar kusa da ƙarshen.
Misali: Binciken Binary don gano ƙimar 12 a cikin tsararrun tsararru a cikin PHP
Bayanin Misali
- Muna farawa da kewayon bincike na farko daga matsayi na farko
left = 0
zuwa matsayi na ƙarsheright = 6
na tsararru. - Muna lissafin tsakiyar tsakiya(tsakiyar) ta hanyar matsakaicin matsayi na hagu da dama;
mid = 3
. Darajar a tsakiyar shine 12. - Muna kwatanta ƙimar a
mid(12
) tare da ƙimar manufa(12) kuma sami wasa, don haka mu koma matsayi na 3. - Algorithm ya ƙare, kuma muna fitar da sakamakon "Value 12 da aka samo a matsayi na 3."