C # Implementation of the binary search algorithm __ algorithm

Source: Internet
Author: User
definition

In computer science, the binary search (binary search) is also called binary lookup (Half-interval search), also known as logarithmic searching (logarithmic search). This is a search algorithm that finds a particular element in an ordered array. principle

The search process starts with an intermediate element of an array. If the middle element is exactly the element to find, the search process terminates, and if a particular element is greater or less than the middle element, it is found in the half greater or less than the middle element, and is compared to the beginning as well as the middle element. If an array of steps is empty, the representation cannot be found. features

This search algorithm reduces the scope of the search to a more general note

This search algorithm is used to find applications in ordered arrays

Can be used directly to find elements in an array, or to insert sorting sample code The following is a binary lookup:

        <summary>
        ///binary search
        ///</summary>
        ///<param name= "arr" ></param>
        /// <param name= "Key" > object to look for </param> public
        static int BinarySearch (int[] arr,int value)
        {
            int Low = 0;
            int high = arr. Length-1;
            while (Low<=high)
            {
                int middle = (low + high)/2;
                if (value = = Arr[middle])
                {
                    return middle;//returns the index of this element directly if found
                }
                else if (value >arr[middle))
                {Low
                    = middle + 1;
                }
                else
                {High
                    = middle-1;
                }
            }
            return-1;//returns-1 if it is not found;
        

Test:
            Int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
            int value = BinarySearch (arr, 4);
            Console.WriteLine (value);

Results:


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.