Algorithm: Binary Lookup method

Source: Internet
Author: User

Enter the code:

/* Copyright (c) 2014, Yantai University School of Computer * All rights reserved. * File name: Sum123.cpp *:    Lin Haiyun * Completion date: January 12, 2015 * Version number: v2.0 * * Problem Description: Given a sorted array so that he can have a find function * Input Description: Number to find * Program output: Location of the number of lookups * /#include <iostream>using namespace Std;const int N=10;int main () {    int a[n]= {1,2,3,4,5,6,7,8,9,10};    int left,right,mid,x;    left=0;    right=n-1;    while (Cin>>x&&left<=right)    {        mid= (left+right)/2;        if (a[mid]==x)        {            cout<< "find number a[" <<mid<< "]" <<endl;        }        if (a[mid]<x)        {            left=mid+1;        }        else        {            right=mid-1;        }    }    return 0;}

Operation Result:



Summarize:

The algorithm is based on the search from left to right, with a while statement control of the loop implementation, the mid of the left to add 1 to continue to find, on the right minus 1 continue to find until found.

Algorithm: Binary Lookup method

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.