Search algorithm (binary search)

1. Introduction binary search

# Describe binary search: 
    binary search for the orderly collection of data from the ordered set, find the target. Every time the target value, compared with the middle element interval, the interval will be reduced by half to find before, until the found the target element to be found. 0. narrow interval or 
    
# binary search Implementation Note: 
    1 . Loop exit condition 
        Low <= High 
        
    2 .mid values 
        in a conventional manner: MID = (High + Low) / 2 
        improved way: MID = Low + (High-Low) / 2 
        ultimate way: MID = Low + ((high-Low) >> 1) 
        
    . 3 .low and high update 
        Low = MID + 1 
        high = mid- 1 
        
 # binary search scenarios limitations: 
     a . binary search order dependent table structure ( array)
      2 . for the binary search is sequenced data
      3 data quantity is too small, not suitable for use binary search

 

2. code implementation

Package cn.anan.util 

/ ** 
  * Learning binary search 
  * / 
Object the BinarySearch { 

  DEF main (args: the Array [String]): Unit = {
     // define an array, the array is an ordered arrangement 
    val arr = Array (0, 1,2,3,4,5,6,7,8,9,10 ) 

    // define the target figures: 7 
    Val. goal = 7 // find the target numeric index position in the array
     // defined Find location, end position, position index binary 
    var Start = 0 
    var End = arr.length. 1- 
    var mID = 0 // loop processing the while (Start <= End) {
       // calculate intermediate position 
      mID = (Start + End) / 2 // for Compare IF (. Goal ==

    

    
    

      
      ARR (MID)) { 
        the println ( "target digital goal:" + goal + "in the array index position:" + MID)
         return 
      } 

      // If the destination number is less than the digital array intermediate position 
      IF (Goal < ARR (MID) ) {
         // end position equal. 1-mID 
        end-mID. 1 = 
      } 

      // if the number is greater than the target, the position of the array intermediate digital 
      IF (goal> ARR (mID)) {
         // start position is equal. 1 + mID 
        start + = mID. 1 
      } 
    } 
  } 

}

 

Guess you like

Origin www.cnblogs.com/itall/p/11210642.html