首页 > 代码库 > 二分搜索 float
二分搜索 float
Given a sorted array of floats, find the index of the number closest to x: Example: {1.2, 2.5, 9.3} x = 5, return 1
#include<iostream>#include<stdlib.h>#include <math.h>using namespace std;float a[] = {1.2, 2.6, 3.4, 4.2, 5.5, 6.7, 7.1, 8.5, 9.8, 9.9};int main() { int n = sizeof(a)/sizeof(int); float f; cout << "Please input the number:" << endl; cin >> f; int low = 0; int high = n - 1; int mid; int index; float diff, diff_l, diff_r; while(low <= high) { int flag1 = 0; int flag2 = 0; mid = low + (high - low)/2; diff = (a[mid] - f) > 0 ? (a[mid] - f) : (f - a[mid]); if(mid - 1 >= low ) { diff_l = (a[mid - 1] - f) > 0 ? (a[mid - 1] - f) : (f -a[mid - 1]) ; flag1 = 1; } if(mid + 1 <= high){ diff_r = (a[mid + 1] - f) > 0 ? (a[mid + 1] -f) : (f - a[mid + 1]); flag2 = 1; } if(flag1 == 1 && flag2 == 1) { if (diff_l >= diff && diff_r >= diff) { index = mid; break; } if (diff_l < diff_r) { high = mid - 1; } else { low = mid + 1; } } else if(flag1 == 1) { if(diff_l >= diff) { index = mid ; break; } else { high = mid - 1; } } else if(flag2 == 1) { if (diff_r >= diff) { index = mid; break; } else { low = mid + 1; } } else { index = mid; break; } } cout << index << endl; return 0;}
二分搜索 float
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。