Binary Search Algorithm wata ingantacciyar hanya ce a cikin Java shirye-shirye, ana amfani da ita don nemo takamaiman ƙima a cikin tsararrun tsararru. Wannan hanya ta ci gaba da raba tsararrun zuwa sassa biyu kuma tana kwatanta ƙimar bincike da kashi na tsakiya.
Yadda Algorithm Binciken Binary ke Aiki
Algorithm na Bincike na Binary yana farawa ta hanyar kwatanta ƙimar bincike tare da ɓangaren tsakiya na tsararru. Idan darajar bincike ta yi daidai da kashi na tsakiya, algorithm din yana mayar da matsayin wannan kashi. Idan ƙimar bincike ta ƙasa da kashi na tsakiya, algorithm ɗin yana ci gaba da bincike a cikin rabin hagu na tsararru. Idan darajar bincike ta fi girma, algorithm ɗin yana ci gaba da bincike a cikin rabin dama na tsararru. Wannan tsari yana maimaitawa har sai an sami ƙimar bincike ko kuma babu ƙarin abubuwan da za a bincika.
Abũbuwan amfãni da rashin amfani Algorithm na Binciken Binary
Amfani:
- Babban Haɓaka: Wannan algorithm yana kawar da rabin abubuwan da ke cikin kowane mataki, yana inganta binciken manyan tsararru.
- Ƙarƙashin Ƙarƙashin Lokaci: Ƙarfin lokaci na wannan algorithm shine O(log n), yana sa ya zama tasiri ga manyan bayanai.
Rashin hasara:
- Bukatun Tsara Tsara: Algorithm ɗin yana aiki ne kawai tare da tsararraki.
Misali da Bayani
Yi la'akari da misali na amfani da Algorithm na Binaryar Bincike don nemo takamaiman lamba a cikin tsararrun lamba a cikin Java.
public class BinarySearchExample {
public static int binarySearch(int[] array, int target) {
int left = 0;
int right = array.length- 1;
while(left <= right) {
int mid = left +(right- left) / 2;
if(array[mid] == target) {
return mid; // Return position if found
} else if(array[mid] < target) {
left = mid + 1;
} else {
right = mid- 1;
}
}
return -1; // Return -1 if not found
}
public static void main(String[] args) {
int[] numbers = { 1, 3, 5, 7, 9, 11, 13, 15 };
int target = 9;
int position = binarySearch(numbers, target);
if(position != -1) {
System.out.println("Element " + target + " found at position " + position);
} else {
System.out.println("Element " + target + " not found in the array");
}
}
}
A cikin wannan misali, muna amfani da Algorithm na Binaryar Bincike don nemo lamba 9 a cikin tsararrun lamba. Algorithm na sake maimaita ta hanyar tsararru kuma yana kwatanta ƙimar bincike tare da ƙimar tsakiya. A wannan yanayin, ana samun lamba 9 a matsayi na 4(0-based index) a cikin tsararru.
Duk da yake wannan misalin yana nuna yadda Algorithm na Binary Search zai iya samun wani abu a cikin tsararrun adadi, kuma ana iya amfani da shi ga sauran yanayin bincike a cikin Java shirye-shirye.