Data Structures and Algorithms Finding binary search

Sequential search

  • When the data stored in the set, such as a list, we say that these data have a linear relationship or order. Each data element stored in the element data relative to other locations. Because the index values ​​are ordered, we can access them in order. The production process is the realization of a search sequential search.
 
  • Sequential search principle analysis:
    • Starting with the first element in the list, we simply move in accordance with the basic order ordering from one element to another, until you find the elements we are looking for or traverse the complete lists. If we traverse a complete list, the elements are searching for does not exist.
 
  • Code implementation: This function takes a list and we are looking for an element as a parameter and returns a Boolean value if present. found a Boolean variable is initialized to False, if we find elements in the list, it is assigned to True.
 
 
 
  • Ordered list: Before we list the elements are placed randomly, so there is no relative order between the elements. If the element ordering in some way, sequential search what happens? We can make it better efficiency in search technology?
 Binary search:
  • For us to achieve an ordered list of search is very useful. In order to find, when we compare with the first element, if the first element is not what we're looking for, then there are at most n-1 elements need to be compared. Binary search is to start from the middle element, rather than find a list in order. If the element is the element we're looking for, we completed the look. If it is not, we can eliminate half the remaining elements using an ordered list of properties. If the element we're looking for is greater than the middle element, you can eliminate the intermediate element and the middle element is smaller than half elements. If the element in the list, certainly a large part of that half. Then we can repeat with half of the big process, continue to start from the middle element, comparing it with what we are looking for content.
 
 
Search DEF (alist, Item): 
    Find = False 
    Low = 0 
    High = len (alist) - . 1 

    the while Low <= High: 
        index # intermediate position 
        MID = (High + Low) // 2 
        IF alist [MID]> Item : 
            High = mid- . 1 
        elif alist [MID] < Item: 
            Low = MID + . 1 
        # find this location 
        the else : 
            find = True
             BREAK 
    return find 

alist = [ . 1,2,5,7,8]
print(search(alist,8))

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/XLHIT/p/11366368.html