假设我们有一个整数'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语句.
它的工作方式与您期望的一样.没问题.
public int find(long searchKey) {
int lowerBound = 0;
int upperBound = nElems - 1;
int currentIndex;
while(true) {
currentIndex = (lowerBound + upperBound) / 2;
if(a[currentIndex] == searchKey)
return currentIndex; // found it!
else if(lowerBound > upperBound)
return nElems; // can't find it
else { // so then divide range
if(a[currentIndex] < searchKey)
lowerBound = currentIndex + 1; // it's in upper half
else
upperBound = currentIndex - 1; // it's in lower half
} // …Run Code Online (Sandbox Code Playgroud)def binarysearch(a, b, tofind, stringarray)
k=(a+b)/2
if a==b
return nil
end
if (stringarray[k]).include? tofind
return stringarray[k]
end
if (stringarray[k]<=>tofind)==1
binarysearch(a,k,tofind,stringarray)
end
if (stringarray[k]<=>tofind)==-1
binarysearch(k,b,tofind,stringarray)
end
if (stringarray[k]<=>tofind)==0
return stringarray[k]
end
end
Run Code Online (Sandbox Code Playgroud)
这是一种二进制搜索算法.a和b是它正在处理的数组索引,tofind是它正在搜索的字符串,而stringarray是一个字符串数组.不幸的是,每次我尝试运行此函数时,我都会收到以下语法错误:
undefined method `include?' for 1:Fixnum (NoMethodError)`
Run Code Online (Sandbox Code Playgroud)
但这不是一个固定点.我是Ruby的新手,所以我很容易错过一些明显的东西.有什么建议?
这是我声明stringarray的地方:( Netbeans说它是一个数组)
strings=Array.new
newstring=""
until newstring=="no" do
newstring=gets.chomp
strings[strings.size]=newstring
end
Run Code Online (Sandbox Code Playgroud) 我想知道是否有办法让Java中的二进制搜索返回值的多个实例.例如,我有一个Items的ArrayList,其中一个字段是一个String数组的关键字.有没有比使用contains()方法的线性搜索更快的方法来按关键字检索项目并将它们存储在单独的集合中?或者通过诸如作者之类的字符串?
...Item...
private String[] keywords;
private String author;
...
Run Code Online (Sandbox Code Playgroud) function binarySearch(value)
{
var startIndex = 0,
stopIndex = words.length - 1,
middle = Math.floor((stopIndex + startIndex) / 2);
while (words[middle] != value && startIndex < stopIndex) {
// adjust search area
if (value < words[middle]) {
stopIndex = middle - 1;
} else if (value > words[middle]) {
startIndex = middle + 1;
}
// recalculate middle
middle = Math.floor((stopIndex + startIndex) / 2);
}
}
Run Code Online (Sandbox Code Playgroud)
我正在以数组格式制作大量单词:
例如 ["a","ab","abc","b"]
按字母顺序。我遇到的问题是修改我的二进制搜索算法以在正确的位置添加单词然后更新?
将单词添加到有序数组中的最佳性能方法是什么?为什么它是最好的方法?
它在C中得到保证1/2 == 0吗?我需要它来实现二进制搜索:
/*
* len is the array length
* ary is an array of ptrs
* f is a compare function
* found is a ptr to the found element in the array
* both i and offset are unsigned integers, used as indexes
*/
for(i = len/2; !found && i < len; i += offset) {
res = f(c->ary[i]);
if (res == 0) {
found = c->ary[i];
}
else {
offset = (res < 0 …Run Code Online (Sandbox Code Playgroud) 我写了一个二进制搜索,如下所示.当我试图找到10时,它没有显示结果.我错过了什么?
// BinarySearch.cpp : Defines the entry point for the console application.
Run Code Online (Sandbox Code Playgroud)
//
#include "stdafx.h"
#include <iostream>
using namespace std;
void BinarySearch(int arr[],int value);
int * insertionshot(int arr[]);
int _tmain(int argc, _TCHAR* argv[])
{
int arr[10] = {1,2,3,10,5,9,6,8,7,4};
int value;
cin >> value ;
static int *ptr;// = new int[10];
ptr = insertionshot(arr);
BinarySearch(ptr,value);
return 0;
}
int * insertionshot(int arr[])
{
int ar[10];
for(int i =0;i < 10; i++)
{
ar[i] = arr[i];
}
int arrlength = sizeof(ar)/sizeof(ar[0]);
for(int …Run Code Online (Sandbox Code Playgroud) 我知道这可以归结为细节,但是当进行二元搜索并且找不到元素时,返回的理性是什么(-(insertion point) -1).特别是-1部分.这就是Java如何做到这一点,我不明白为什么他们制定了惯例-1而不仅仅是-(insertion point).显然,否定的是表明在数组/列表中实际找不到该值.我猜它来自C,它更容易做一些否定和减去一个的按位操作.
注意:我见过使用这种约定用C,C++和Java编写的代码,我想知道约定来自哪里?
我有一个LinkedList的n随机Integer升序秒.
如果我Collections.binarySearch在该列表上使用它,它适用于任何n我尝试过的.
当我换行LinkedList与AbstractList然而,对于n>10000二进制搜索开始表现得非常奇怪.
它不是运行适当的二进制搜索,而是遍历整个列表.
我有一个"file"包含升序的随机数,其中每行包含一个数字.
我想二进制搜索"file"并找到"line number"给定数字的索引(或).
一个简单的解决方案就是读取整个文件并将每个数字放入a中LinkedList,然后使用Collections.binarySearch它LinkedList.
现在,让我们说我得到的信息是,从中读取一行"file"是一项代价高昂的操作.
我试图做的,尽量减少我必须阅读的时间"file",是"模拟"那个LinkedList,并AbstractList在每次使用时使用一个地方get(int index),AbstractList我只是index从中读取行"file".
当我的AbstractList大小是<1000,当我尝试更大的列表时,二进制搜索似乎停止工作,并且只是迭代所有AbstractList(从第一个节点到最后一个节点),这似乎工作得很好.
我似乎已经将问题缩小到使用带有二进制搜索的大型AbstractList.我不确定为什么会这样,并且会喜欢一些帮助.
我已经包含了"长版",以防有人能够提出另一种解决方案.
谢谢!
在二进制搜索中,我们通常有低变量和高变量,通常有一个while循环测试低<=高,如此代码(来自维基百科)所示:
int SortedArray[max] = {....}
int BinarySearch (int key)
{
int start = 0;
int end = max - 1;
int mid;
while (start <= end)
{
mid = (start + end) / 2;
if (key == a[mid])
return mid;
else if (key < a[mid])
end = mid - 1;
else start = mid + 1;
}
return -1;
}
Run Code Online (Sandbox Code Playgroud)
在学习二进制搜索时,我总是被教导低<=高的方法,但是当看到其他实现时,我看到很多人都在做(低<高).
一个对另一个有优势吗?在我自己的原生实现中,我执行<=方法,但是当我将其切换为<时,搜索失败.
使用一个与另一个有经验法则吗?
binary-search ×10
java ×5
algorithm ×4
arrays ×3
c ×3
search ×2
abstract ×1
c++ ×1
collections ×1
integer ×1
javascript ×1
linked-list ×1
math ×1
ruby ×1