Binary search of Python algorithm

Source: Internet
Author: User

Description: Most of the code is found on the Internet, several code ideas summed up

Usually write algorithm, used to write in C language, it seems clear thinking, but if once the idea is determined, and do not want to hit the draft, want to quickly write down to see the effect, or Python write faster, also see personal hobbies, internship when there is a colleague for Python in the Indentation control code block various spray .... He thought it was appropriate to use curly braces ... How to say, suitable for their own is the best. My personal problem is, write a few days C, to go to Python, the code still has a C shadow. such as braces, such as forgetting in the while or this for, if, else and so on after adding ":", and if you write a few days python, to go to C, will forget to declare some variables, directly to use, when running, the various variables are undefined. Here to give yourself a wake up, think more and more hands-on.

Today inadvertently see two points to find, originally thought very simple code, a few lines on the end, and later saw a comparison of cattle code, only to find that people than people damned is the eternal truth, in order not to die, but also should not be dead code to learn to do Ah, two points find the principle is very simple, is in an ordered sequence, The lookup code is half the comparison rather than one to one

The simplest binary lookup non-recursive code is as follows:

int search (int array[], int n, int v) {    int left, right, middle;    left = 0, right = n-1;    while (left <= right)    {        middle = (left + right)/2;        if (Array[middle] > V)        {right            = middle;        }        else if (Array[middle] < V)        {left            = middle;        }        else        {            return middle;        }    }    return-1;}

Input: Array arrays, array size n, find element V

Output: V in position, not found return-1

############################################################################################################### ######################

A recursive code is written below:

#include <stdio.h>int search (int arr[],int low,int high,int key) {        int mid = (Low+high)/2;        if (Low > High)                return-1;        if (arr[mid] = = key)                return mid;        else if (Arr[mid]>key)                return search (Arr,low,mid-1,key);        else                return search (Arr,mid+1,high,key);} int main () {        int arr[101] = {1,2,3,4,87,90,100};        int low = 0,high = 8,key = 87,ret;        ret = search (Arr,low,high,key);        if (ret! =-1)                printf ("The Return is%d", ret);        else                printf ("FBI warning:the return Is-1,not find the Key");}

Do not know the recursion of the classmate, please refer to the recursive spit groove ... The first time I heard the teacher say Recursive , this is what I think.


But in fact, recursion is like this.


Okay, no, two points to find this code in fact, it is still a bit of a problem, such as this three judgments, two comparisons, there is

In the body of the loop, the expression is used when calculating the intermediate position:

Mid = (left + right)/2;
If the sum of left and right exceeds the representation range of the type, then middle will not get the correct value.
So, the more prudent approach should be this:
Mid = left + (right-left)/2; Let's optimize the Python code as follows:

def search (arr,n,v): Left        =-1 Right        = n while (left+1! = right        ):                mid = left+ (right-left)/2                if (arr[ MID] < V): Left                        = Mid                else: Right                        = Mid        if (right >= n or arr[right]! = V): Right                = 1        retur n rightif __name__ = = ' __main__ ':        arr = [1,2,4,23,87,90,555,1222,1444]        n = len (arr)        ret = Search (arr,n,87 )        PRINT ret

Look at the C code:

int search (int array[], int n, int v) {    int left, right, mid;    left =-1, right = N;    while (left + 1! = right)    {        mid = left + (right-left)/2;        if (Array[mid] < V)        {left            = mid;        }        else        {Right            = mid;        }    }    if (right >= n | | array[right]! = V)    {Right        =-1;    }    return right;}


This code first not reasoning do not understand, the light return value only with right this is very good, this looks very simple, but very essence of feeling have? Look at while the judge, Left+1!=right is not very hot? I understand BA



Binary search of Python algorithm

Related Article

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.