我想找到第一個整數在整數數組中的索引,它是< = key。我可以在log2(N)+1比較中使用二進制搜索。只有log2(N)比較纔有可能?爲什麼我的二進制搜索需要額外的比較? log2(N)+1
// Returns the index of the first integer in keys <= key. size must be a power of 2.
unsigned find(int key, int* keys, unsigned size) {
int* origKeys = keys;
for (int i = 0; i < log2(size); i++) {
size /= 2;
if (keys[size] < key)
keys += size;
}
unsigned i = unsigned(keys - origKeys);
// Not only is this step messy, because it doesn't fit the loop, but
// now we have log2(n) + 1 comparisons.
if (*keys < key)
i++;
return i;
}
請問你的log 2函數返回對數的天花板或地板? – templatetypedef
大小是每個註釋的2次冪,所以它沒關係 – Eloff
對於未排序的數組,無論如何,最壞情況的複雜度將是O(N)。如果您沒有任何元素<=鍵,則仍然需要掃描整個陣列=> O(N)時間複雜度。 –