बाइनरी सर्च एल्गोरिदम बड़े संख्याओं की एक सरणी को तेजी से खोजता है, इसे अक्सर विभाजन और विजय के रूप में संदर्भित किया जाता है।
public class BinarySearch
{
public int BinarySearch(int[] items, int searchValue)
{
int left = 0;
int right = items.Length - 1;
while (left <= right)
{
var middle = (left + right) / 2;
//If the searchValue is in the center, we found it!
if(items[middle] == searchValue)
{
return middle;
}
//If the searchValue is less than the current middle, we set the right to (middle - 1)
//Because the searchValue is in the lower half of the items.
if(searchValue < items[middle])
{
right = middle - 1;
}
//If the searchValue is greater than the current middle, we set the right to (middle + 1)
//Because the searchValue is in the higher half of the items.
else
{
left = middle + 1;
}
} // now that we've either found the item and returned it or we've reset our search boundaries
// we'll search it again.
// Not found.
return -1;
}
} लेखक: Chuck Conway एक AI इंजीनियर हैं जिनके पास सॉफ्टवेयर इंजीनियरिंग का लगभग 30 साल का अनुभव है। वह व्यावहारिक AI सिस्टम बनाते हैं—कंटेंट पाइपलाइन, इंफ्रास्ट्रक्चर एजेंट, और ऐसे टूल जो वास्तविक समस्याओं को हल करते हैं—और अपनी सीख को साझा करते हैं। सोशल मीडिया पर उनसे जुड़ें: X (@chuckconway) या YouTube और SubStack पर उनसे मिलें।