Skip to content

পোস্ট

একটি বাইনারি সার্চ বাস্তবায়ন

২ ডিসেম্বর, ২০২০ • 1 মিনিট পড়া

একটি বাইনারি সার্চ বাস্তবায়ন

বাইনারি সার্চ অ্যালগরিদম দ্রুত একটি বড় সংখ্যার অ্যারে অনুসন্ধান করে, এটি প্রায়ই ভাগ করো এবং জয় করো হিসেবে উল্লেখ করা হয়।

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;
    }
}

লেখক: চাক কনওয়ে সফটওয়্যার ইঞ্জিনিয়ারিং এবং জেনারেটিভ এআই-তে বিশেষজ্ঞ। তার সাথে সোশ্যাল মিডিয়ায় যোগাযোগ করুন: X (@chuckconway) অথবা তাকে YouTube-এ দেখুন।

↑ উপরে ফিরে যান

আপনি এগুলোও পছন্দ করতে পারেন