Binary search method C# implementation

大家讲道理
Release: 2016-11-10 09:25:41
Original
2066 people have browsed it

public int FindPosition(int num, int[] arr)  
        {  
            int left = 0;  
            int right = arr.Length - 1;  
   
   
            while (left < right - 1)  
            {  
                if (arr[left] == num)  
                {  
                    return left;  
                }  
                if (arr[right] == num)  
                {  
                    return right;  
                }  
   
   
                int middle = (left + right) / 2;  
                if (num == arr[middle])  
                {  
                    return middle;  
                }  
                else if (num < arr[middle])  
                {  
                    right = middle;  
                }  
                else 
                {  
                    left = middle;  
                }  
   
   
            }  
            return -1;  
        }
Copy after login

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!