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, appear clear thinking. But suppose once the idea is determined, and do not want to make a draft. Want to write down at high speed to see the effect, or Python write faster. Also see personal hobbies. Internship with 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. For example, a brace problem, such as forgetting to add ":" After the while or the for, if, else, and so on. And suppose you write for a few days python, to go to C. Will forget to declare some variables. Just take it and use it. At the time of execution, various variables are not defined. Give yourself a wake up here. Think more and do more.

Today, I accidentally saw a two-point search. Would have thought very easy code. A few lines ended, and later saw a comparison of the cattle code. It is the eternal truth that man is more damned than man. In order not to die, but also to learn the code should not be dead, the binary search principle is very easy, is in an ordered sequence. The lookup code is half the comparison rather than one.

The simplest binary finds non-recursive codes such as the following:

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 of arrays. Array size n, finding element V

Output: V in position, not found return-1

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

Here's a recursive code:

#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");}

Students who do not know the recursion. Please refer to the recursive spit groove ... The first time I heard the teacher say Recursive , this is what I think.

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvcmvjc3lzbww=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast ">

But the fact that recursion is this


All right, that's not a rip. Binary search This code is actually a bit of a problem if you look at it in detail. Let's say this three-time deduction. Two times comparison. And 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.
Therefore, the more prudent approach should be this:
Mid = left + (right-left)/2; Let's optimize it, Python code like this:

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 does not understand, the light return value just with right this is very good, so look very easy, but very essence of feeling there? Look at while the inference, 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.