Find a number from n data

Source: Internet
Author: User

n data is described with an array a, and the lookup object is described by X.

We can compare n data to a Lookup object in turn, and we may or may not find it. This is a sequential lookup method, please the reader programming implementation.

More than sequential lookup is the binary lookup, or the second-order lookup method. Binary lookup requires n data to be sorted in order to find it quickly. Assume that n data has been sorted from small to large. The data found is described with its subscript k. Whether to find a description with a flag variable flag.

The lookup problem is converted to K in the interval [o,n 11]. First compute the point D, if A[d] an x, then k-d; if a[d]>x, the lookup interval shrinks to [o,d], and if a[d]<x, the lookup interval shrinks to [D,n 11]. Either find, or look for the interval to shrink by half, continue binary lookup.

The procedure is as follows:

float serach(a,n,x)/*折半查找函数*/
float a[],x;
int n:
{int k,flag;
int b=O,e=n一1,d;
flag=O;
do
{d=(b+e)/2;
if(a[d]==x){k=d;flag=1;}
else if(a[d]>x)e=d;
else b=d:
)while(b<e&&!flag);
if(flag==O)k=O;/*没找到*/
return(k);
}

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.