首页 > 代码库 > 二分查找函數
二分查找函數
找到,返回下標;
int binary_search(const int* a, int low_position, int high_position, const int key) { high_position--; while(low_position < high_position) { int mid_position = (low_position+high_position) >> 1; if(a[mid_position] == key) return mid_position; else if(a[mid_position] < key) low_position = mid_position + 1; else high_position = mid_position - 1; } return -1; }
找到,返回success
char* binary_search(const int* a, int low_position, int high_position, const int key) { high_position--; char **result = {"success", "fail"}; while(low_position < high_position) { int mid_position = (low_position+high_position) >> 1; if(a[mid_position] == key) return *result; else if(a[mid_position] < key) low_position = mid_position + 1; else high_position = mid_position - 1; } return *(result+1); }
二分查找函數
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。