二分法查找

using  System;
using  System.Collections.Generic;
using  System.Text;

namespace  BinarySearch
{
    
class BinarySearch
    
{
        
static void Main(string[] args)
        
{
            
int[] iArray = new int[] 1234567891011121314151617181920 };
            
for (int i = 0; i < iArray.Length; i++)
                Console.Write(iArray[i] 
+ ",");
            Console.WriteLine(
"请输入您要查找的数字:");
            
int ikey = Convert.ToInt32(Console.ReadLine());
            BinarySearch bs 
= new BinarySearch();
            
int iResult = bs.iBinarySearch(ikey, iArray);
            Console.WriteLine(iResult);
            Console.ReadLine();
            
return;
        }

        
public int iBinarySearch(int key, int[] iArray)
        
{
            
int iLeft = 0;
            
int iRight = iArray.Length - 1;
            
while (iLeft <= iRight)
            
{
                
int iMiddle = (iLeft + iRight) / 2;
                
if (key == iArray[iMiddle])
                    
return iMiddle;
                
else if (key > iArray[iMiddle])
                    iLeft 
= iMiddle + 1;
                
else
                    iRight 
= iMiddle - 1;
            }

            
return -1;
        }

    }

}
 

你可能感兴趣的:(二分法查找)