// 折半查找.cpp : 定義控制檯應用程序的入口點。 // #include "stdafx.h" #include<iostream> using namespace std; int binarySearch(int a[],int length,int k) { int left=0;int right=length-1; int count = 0; while(left<=right) { count=count+1; int index=left+(right-left)/2; if(a[index]>k) right=index-1; else if(a[index]<k) left=index+1; else return k; } return -1; } int main() { int a[]={1,2,3,4,5,6,7,8,9,10,11,12,14}; int k=4; cout<<binarySearch(a,13,k); system("pause"); return 0; }