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