二分查找java代码
发布时间:2020-12-14 04:46:19 所属栏目:百科 来源:网络整理
导读:public int find( long searchKey){ int i; int begin = 0 ; int end = nElems - 1 ; while ( true ){ i = (begin + end) / 2 ; if (searchKey == a[i]){ return i; } else if (begin end) { return -1 ; } if (searchKey a[i]) { begin = i + 1 if (searchK
public int find(long searchKey){ int i; int begin = 0; int end = nElems - 1; while(true){ i = (begin + end) / 2; if (searchKey == a[i]){ return i; } else if (begin > end) { return -1; } if (searchKey > a[i]) { begin = i + 1if (searchKey < a[i]) { end = i - 1; } } } 其中a是待查有序数组,searchKey是待查数值。 查询次数为num = log2(a.length)即数组长度的对数 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |