【发布时间】:2014-11-27 19:46:30
【问题描述】:
假设我已经订购了NSArray 的NSNumbers:
2, 4, 8, 15, 16, 20 // for simplicity let's treat it as array of int's instead of NSNumbers
现在我需要找到最接近的索引,比如value == 19。
searchValue = 19;
minIndex = 0;
maxIndex = array.count - 1;
currentIndex = (int)floorf(maxIndex / 2.f);
while (maxIndex - minIndex == 1) {
if (array[currentIndex] < searchValue) { // go right
minIndex = currentIndex;
} else if (array[currentIndex] > searchValue) { // go left
maxIndex = currentIndex;
} else { // exact value, rather low probability of happening
return currentIndex;
}
currentIndex = (int)floorf((maxIndex - minIndex) / 2.f);
}
// let's check values around, who has smaller difference
int leftDifference = (currentIndex - 1 >= 0) ? abs(array[currentIndex - 1] - searchValue) : INT_MAX;
int rightDifference = (currentIndex + 1 < array.count) ? abs(array[currentIndex + 1] - searchValue) : INT_MAX;
int centralDifference = abs(array[currentIndex] - searchValue);
if (leftDifference < rightDifference && leftDifference < centralDifference) {
return currentIndex - 1;
} else if () {
return currentIndex + 1;
} else {
return currentIndex;
}
这是我能想象到的最快的方式,也许有人有不同的想法?如何改进算法?
我查看了 egSOF question,但它搜索值而不是索引,并通过浏览所有值来实现。在索引的情况下,我们不必浏览整个数组。
【问题讨论】:
-
为什么需要优化这个特定的操作?我建议您最好使用更快的容器类,而不是优化搜索。即使您检查每个元素,搜索也是 O(n)
-
@RogerNolan 我已经有一个数组,其中包含我的自定义类的许多对象。在其他之间,它也有我想要执行搜索的这些值。我不想复制所有这些,甚至是选定的值,因为这需要时间和内存。要更改容器类,我需要更改几乎整个应用程序,这是不可能完成任务的时间。我需要对其进行优化,因为该算法将每秒调用一次(计时器...)。
-
看起来很适合binary search。
标签: objective-c algorithm