C# binary search method

=============================

Binary search , also known as binary search algorithm , binary search , is a search algorithm to find a specific element in an ordered array .

A The search process starts from the middle element of the array. If the middle element is exactly the element to be found, the search process ends;

B If a particular element is greater than or less than the middle element, search in the half of the array that is greater than or less than the middle element, and start the comparison from the middle element as if it were the beginning.

C If the array is empty at a certain step, it means it cannot be found. This search algorithm reduces the search range by half for each comparison.

The time complexity halved search reduces the search area in half each time, and the time complexity is O\left( \log n  \right). (n represents the number of elements in the set) space complexityO\left(  1  \right)

==========

code show as below:

        ///  <summary> 
        /// Binary search
         ///  </summary> 
        ///  <param name="arr"></param> 
        ///  <param name="low"> Start index 0 </param > 
        ///  <param name="high"> End Index </param> 
        ///  <param name="key"> Object to find </param> 
        ///  <returns></returns> 
        public  static  int BinarySearch( int [] arr, int low, int high, int key)
        {
            int mid = (low + high) / 2;
            if (low > high)
                return -1;
            else
            {
                if (arr[mid] == key)
                    return mid;
                else if (arr[mid] > key)
                    return BinarySearch(arr, low, mid - 1, key);
                else
                    return BinarySearch(arr, mid + 1, high, key);
            }
        }


The method call looks like this:

int[] y = new int[] {1,2,3,4,33,5,6,7,8,,45,9,10,11,12,13,88 };
int rr = BinarySearch(y, 0, y.Length - 1, 13);
Message.Box(rr);    //12

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325393480&siteId=291194637
Recommended