标签:
//c实现
1 #include "stdafx.h" 2 #include "stdlib.h" 3 4 5 int _tmain(int argc, _TCHAR* argv[]) 6 { 7 int a[10] = {0,1,3,4,6,7,9,11,12,15}; 8 int low,high,mid,key,flag; 9 key = 7;flag = -1; 10 low = 0;high = 10; 11 while(low<high) 12 { 13 mid = (low + high)/2; 14 if(a[mid]>key) 15 high = mid - 1; 16 else if(a[mid]<key) 17 low = mid + 1; 18 else 19 { 20 flag = mid; 21 break; 22 } 23 } 24 printf("%d",flag); 25 system("pause"); 26 return 0; 27 }
//lua实现
1 function BinarySearch_t(t,key) 2 local low,flag,high,mid 3 low = 1 4 high = #t 5 flag = -1 6 while(low<high) 7 do 8 mid = (low + high)/2 9 if(t[mid]>key) then 10 high = mid - 1 11 elseif(t[mid]<key) then 12 low = mid + 1 13 else 14 flag = mid 15 break 16 end 17 end 18 return flag 19 end 20 --无法运行成功,报错:attempt to compare number with nil 21 --line 9 22 local ta = {0,2,3,4,6,8,9,11,12} 23 --line 24 ↓ 24 print(BinarySearch_t(ta,3))
标签:
原文地址:http://www.cnblogs.com/nightcatcher/p/4448685.html