The basic search algorithm

The basic search algorithm are: sequential search, binary search,

Sequential search is very short answer is that through each element of the array, is achieved by the number of unknown origin found by comparing a for loop to get.

Sequential search does not need to sort the array, the disadvantage is low efficiency, time-consuming, because to traverse.

Binary search is to find a way to improve efficiency, provided that an orderly array, if not need to get an array of first use sorting algorithms (bubble, select, insert) to sort.

Use of binary search is that dichotomy, soon array has split in two, half and half reduced contrast range.

Dichotomy code implementation:

class Test
{
   public static void Main()
   {
       int[] number=new int[]{11,22,33,44,55,66,77,88,99};
       int  sValue=33;
       int index;
       index=Dichotomy(number,sValue);
       Console.WriteLine("{0}",  index);
    }

   public static int  Dichotomy(int[] num,int sValue)
  {  
        int upper=num.Length()-1;
         int lower=0;
       int mid= (upper+lower)/2;
       while( lower<=upper)
      {
            if(num[mid]==sValue)
           { 
                 return  mid;  //存在返回下标
            }
              if(num[mid]>sValue)
            { 
                upper=mid-1;
            }
               IF (NUM [MID] < sValue) 
          { 
                 Lower = MID + . 1 ; 
          } 
        return - . 1 ; // absent -1 
       }

 public static int  Rdichotomy(int[] num,int sValue)
  {  
        int upper=num.Length()-1;
         int lower=0;
       int mid= (upper+lower)/2;
if(lower>upper)
{
return -1;
} else
{
           IF (NUM [MID] == sValue) 
           { 
                 return MID; // return subscript presence 
            }
          if(num[mid]>sValue)
            {
            dichotomy(int[] num,int sValue)
           }
            if(num[mid]>sValue)
            {
            dichotomy(int[] num,int sValue)
           }

} if(num[mid]>sValue) { upper=mid-1; } if(num[mid]<sValue) { lower=mid+1; } return -1;//不存在返回-1 }

}
}

 

Guess you like

Origin www.cnblogs.com/lyjbk/p/11396348.html