二分查找(美国的各种硬币名称)
Binary_search
#include <stdio.h>
struct {
int amount;
char *name;
}coins[]={
{1,"penny"},
{5,"nickel"},
{10,"dime"},
{25,"quater"},
{50,"half-dollar"},
};
//binary search can be used only under the circumstance that the elements in the list have been sorted
int main(){
int key = 25;
int len;
len = sizeof (coins)/sizeof(coins[0]);
int ret = -1;//the return of the binary search
int left = 0;
int right = len-1;
while(left < right){
int mid = (left+right)/2;
if (coins[mid].amount == key){
ret = mid;
break;
}else if(coins[mid].amount > key){ //the array is monotonically increasing
right = mid-1;
}else{
left = mid+1;
}
}
if (ret!=-1){
printf("%s\n",coins[ret].name);
}else{
printf("not found!");
}
return 0;
}