Python uses a binary method to find the specified element in a sequential table

Source: Internet
Author: User

Dichotomy is a fast-finding method, with a low time complexity and simple logic, which is generally divided by 2 divided by 2 ...

For example, to find the location of a keyword key in an ordered list, first confirm the list's median mid, which is divided into three scenarios:

If LIST[MID] < key, indicate that key is on the right of the median;

If List[mid] > key, indicate that key is on the left of the median;

If list[mid] = key, indicates that key is in the middle of the median;

The range shrinks by half each time, writing a while loop to know until it is found.

Binary lookup is very fast and very common, but the only requirement is that the array is ordered

The code is as follows

1 #!/usr/bin/python2.72 #-*-coding:utf-8-*-3 4 defBinarySearch (Lista, key):5     #record the highest and lowest bits of an array6Min =07max = Len (lista)-18 9     ifKeyinchlista:Ten         #build a dead loop until you find the key One          whileTrue: A             #get the median number -Mid = (min + max)/2 -             #key to the left of the array the             ifLista[mid] >Key: -max = Mid-1 -             #key to the right of the array -             elifLista[mid] <Key: +Min = mid + 1 -             #key in the middle of the array +             elifLista[mid] = =Key: A                 PrintSTR (KEY) +"in the array, the first"+ STR (MID) +"a location" at                 returnLista[mid] -     Else: -         Print("no such number!") -  -  - if __name__=="__main__": inarr = [1, 6, 9, 15, 26, 38, 49, 57, 63, 77, 81, 93] -      whileTrue: toKey = input ("Please enter the number you want to find:") +         ifKey = =" ": -             Print("Thanks for using! ") the              Break *         Else: $BinarySearch (lista, int (key))

Python uses a binary method to find the specified element in a sequential table

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.