在C中以各种类别对整数进行bin/map的优雅方法是什么?

Sie*_*geX 0 c algorithm search binary-search

假设我们有一个整数'x'和'n'可能的值'x'可以映射/分箱到.在C中有一个优雅的方法是有一个函数可以将最接近的'nth'值返回给x?

伪代码示例;

int x = 40;
int res;
int bins[] = { 0, 20, 80, 200 }; /* Sorting is guaranteed */

res = int_bin(x, bins);
assert(res == 20); /* 40 is closer to 20 than 80 */

x = 150;

res = int_bin(x, bins);
assert(res == 200); /* 150 is closer to 200 than 80 */
Run Code Online (Sandbox Code Playgroud)

优雅我的意思不仅仅是一堆if/else if/else语句.

Jam*_*lis 5

如果列表已排序,那么您只需对值进行二进制搜索即可.

如果搜索没有在列表中找到该值,您将知道该值在列表中的位置.然后,您可以将该值与该索引处的元素和前一个索引处的元素进行比较(如果索引显然不是零),并查看哪个更接近.