Algorithms - Find

Linear search

Sequentially from start to finish check an element in the list, the time complexity is O (n)

DEF Search (arr, n-, X): 
  
    for I in Range (0, n-): 
         IF (arr [I] == X): 
             return I; 
     return -1 ; 
  
# find the character D in the array arr 
arr = [ ' A ' , ' B ' , ' C ' , ' D ' , ' E ' ]; 
X = ' D ' ; 
n- = len (ARR); 
Result = Search (ARR, n-, X) 
IF (Result == -1 ): 
     Print ( " element not in the array " ) 
 the else : 
     Print ( " index of the element in the array is " , Result);

 

Binary search

From one ordered search algorithm whether there is an element of the list. Search process from the middle of the array elements, if the intermediate element the element is just looking for, the search process ends; if a particular element is greater than or less than the intermediate element in the array is greater or less than half that of the intermediate element lookup, and Like start start comparing the middle element. If the array is empty at some stage, it represents not found. This search algorithm so that each comparison search reduced by half. 

# Returns the index of arr x, if there is no return -1 
DEF binarySearch (arr, L, R & lt, x): 
  
    # substantially Analyzing 
    IF R & lt> = L: 
  
        MID = int (L + (R & lt - L) / 2 ) 
  
        # element whole a good intermediate position 
        IF ARR [mID] == X: 
             return mID 
          
        # elements less than the intermediate position of the elements, the elements just need to compare the left 
        elif ARR [mID]> X: 
             return binarySearch (ARR, L, mid- . 1 , X) 
  
        # element is greater than the intermediate position of the element, the comparison element again just right 
        the else : 
             return binarySearch (ARR,. 1 + mID , R & lt, X) 
  
    the else : 
         # absent
        return -1 # test array 
ARR = [2,. 3,. 4, 10, 40 ] 
X = 10 # function call 
Result = binarySearch (ARR, 0, len (ARR) -1 , X) IF Result = -1! : 
     Print ( " element index in the array is D% " % Result)
 the else : 
     Print ( " element not in the array " )
  

  

  

 

Guess you like

Origin www.cnblogs.com/hf8051/p/11459295.html