标签:
// 折半查找.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; }
标签:
原文地址:http://my.oschina.net/u/2350638/blog/499926