文章目录
1、概述2、软件实现1.1、循环1.2、递归
1、概述
关于二分法查找可以使用循环语句去遍历数组或者使用递归的方式实现。
2、软件实现
下面的例子是在已知转向角和转弯半径的对应关系的情况下,反向由转弯半径求取转向角。分别用循环和递归的方式,分别去查找对应的转向角。
1.1、循环
float SteeringAngleFindingLoop(uint16_t left_id
,uint16_t right_id
,float radius
)
{
uint16_t middle_id
;
if(radius
> 0)
{
while( (right_id
- left_id
) > 1)
{
middle_id
= (uint16_t
)((left_id
+ right_id
) * 0.5);
if(radius
< SteerAngle2Radius
[middle_id
][0])
{
left_id
= middle_id
;
}
else if(radius
> SteerAngle2Radius
[middle_id
][0])
{
right_id
= middle_id
;
}
else
{
return middle_id
;
}
}
return (left_id
+ right_id
) * 0.5;
}
else
{
while( (right_id
- left_id
) > 1)
{
middle_id
= (uint16_t
)((left_id
+ right_id
) * 0.5);
if(-radius
< SteerAngle2Radius
[middle_id
][1])
{
left_id
= middle_id
;
}
else if(-radius
> SteerAngle2Radius
[middle_id
][1])
{
right_id
= middle_id
;
}
else
{
return -middle_id
;
}
}
return -(left_id
+ right_id
) * 0.5;
}
}
1.2、递归
float SteeringAngleFindingCallback(uint16_t left_id
,uint16_t right_id
,float radius
)
{
uint16_t middle_id
;
middle_id
= (left_id
+ right_id
) * 0.5;
if(radius
> 0)
{
if( (right_id
- left_id
) > 1)
{
if(radius
< SteerAngle2Radius
[middle_id
][0])
{
return SteeringAngleFindingCallback(middle_id
,right_id
,radius
);
}
else if(radius
> SteerAngle2Radius
[middle_id
][0])
{
return SteeringAngleFindingCallback(left_id
,middle_id
,radius
);
}
else
{
return middle_id
;
}
}
else
{
return (left_id
+ right_id
) * 0.5;
}
}
else
{
if( (right_id
- left_id
) > 1)
{
if(-radius
< SteerAngle2Radius
[middle_id
][1])
{
return SteeringAngleFindingCallback(middle_id
,right_id
,radius
);
}
else if(-radius
> SteerAngle2Radius
[middle_id
][1])
{
return SteeringAngleFindingCallback(left_id
,middle_id
,radius
);
}
else
{
return -middle_id
;
}
}
else
{
return -(left_id
+ right_id
) * 0.5;
}
}
}