查找算法复杂度及特点

· · 算法·理论

稍稍借助了一下夸克AI嘻嘻
查找算法 时间复杂度 (最好) 时间复杂度 (平均) 时间复杂度 (最坏) 空间复杂度 数据结构要求 特点
顺序查找 (Sequential Search) O(1) O(n) O(n) O(1) 无序数组/链表 最简单,无需预处理。效率低,但适用性广。
二分查找 (Binary Search) O(1) O(\log n) O(\log n) O(1) 有序数组 效率高,但要求数据预先排序,不适合频繁插入删除的场景。
插值查找 (Interpolation Search) O(1) O(\log \log n) O(n) O(1) 有序数组 是二分查找的改进,适用于元素分布均匀的数组。
斐波那契查找 (Fibonacci Search) O(1) O(\log n) O(\log n) O(1) 有序数组 也是二分查找的改进,通过斐波那契数列进行分割,据说在特定存储介质上性能更好。
哈希查找 (Hash Search) O(1) O(1) O(n) O(n) 哈希表 通过哈希函数直接计算地址,理想情况下速度最快。但需要额外空间,并且需要处理哈希冲突。
二叉搜索树查找 (BST) O(1) O(\log n) O(n) O(n) 二叉搜索树 在平衡状态下性能优秀,能支持动态插入、删除和范围查找。不平衡时退化为链表。
B树 / B+树查找 O(\log n) O(\log n) O(\log n) O(n) B树 / B+树 专为磁盘等外部存储设计,通过增大节点容纳更多关键字来降低树的高度,减少I/O次数。数据库和文件系统中应用广泛。
跳表 (Skip List) O(1) O(\log n) O(\log n) O(n) 动态有序数据 一种概率性的数据结构,通过多层链表实现快速查找,同时支持高效的插入和删除。

下面是一条华丽的分割线

1. 顺序查找 (Sequential Search)

思路: 从头到尾遍历容器,逐个比较元素。

#include <vector>
#include <functional>

template<typename Container, typename T, typename Compare = std::equal_to<typename Container::value_type>>
typename Container::const_iterator sequentialSearch(const Container& container, const T& target, Compare comp = Compare{}) {
    auto it = container.begin();
    for (; it != container.end(); ++it) {
        if (comp(*it, target)) {
            return it; // 找到,返回迭代器
        }
    }
    return container.end(); // 未找到
}

// 返回下标版本
template<typename Container, typename T, typename Compare = std::equal_to<typename Container::value_type>>
int sequentialSearchIndex(const Container& container, const T& target, Compare comp = Compare{}) {
    for (size_t i = 0; i < container.size(); ++i) {
        if (comp(container[i], target)) {
            return static_cast<int>(i);
        }
    }
    return -1; // 未找到
}

// 返回布尔值版本
template<typename Container, typename T, typename Compare = std::equal_to<typename Container::value_type>>
bool sequentialSearchBool(const Container& container, const T& target, Compare comp = Compare{}) {
    return sequentialSearch(container, target, comp) != container.end();
}

示例用法:

std::vector<int> vec = {3, 1, 4, 1, 5};

// 1. 返回迭代器
auto it = sequentialSearch(vec, 4);
if (it != vec.end()) {
    std::cout << "Found at index: " << std::distance(vec.begin(), it) << ", value: " << *it << std::endl;
} // 输出: Found at index: 2, value: 4

// 2. 返回下标
int index = sequentialSearchIndex(vec, 1);
if (index != -1) {
    std::cout << "Found '1' at index: " << index << std::endl; // 输出: Found '1' at index: 1
}

// 3. 返回布尔值
bool found = sequentialSearchBool(vec, 9);
std::cout << "Is '9' in the vector? " << (found ? "Yes" : "No") << std::endl; // 输出: Is '9' in the vector? No

2. 二分查找 (Binary Search)

思路: 在有序容器中,每次都与中间元素比较,从而将搜索范围缩小一半。

#include <vector>
#include <functional>

template<typename Container, typename T, typename Compare = std::less<typename Container::value_type>>
typename Container::const_iterator binarySearch(const Container& sortedContainer, const T& target, Compare comp = Compare{}) {
    auto left = sortedContainer.begin();
    auto right = sortedContainer.end();

    while (left != right) {
        auto mid = left + std::distance(left, right) / 2;
        if (comp(*mid, target)) {
            left = mid + 1;
        } else if (comp(target, *mid)) {
            right = mid;
        } else {
            return mid; // 找到
        }
    }
    return sortedContainer.end(); // 未找到
}

template<typename T, typename Compare = std::less<T>>
int binarySearchIndex(const std::vector<T>& sortedVec, const T& target, Compare comp = Compare{}) {
    int left = 0, right = sortedVec.size();
    while (left < right) {
        int mid = left + (right - left) / 2;
        if (comp(sortedVec[mid], target)) {
            left = mid + 1;
        } else if (comp(target, sortedVec[mid])) {
            right = mid;
        } else {
            return mid;
        }
    }
    return -1; // 未找到
}

template<typename Container, typename T, typename Compare = std::less<typename Container::value_type>>
bool binarySearchBool(const Container& sortedContainer, const T& target, Compare comp = Compare{}) {
    return binarySearch(sortedContainer, target, comp) != sortedContainer.end();
}

示例用法:

std::vector<int> sortedVec = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

auto it = binarySearch(sortedVec, 7);
if (it != sortedVec.end()) {
    std::cout << "Found '7' at index: " << std::distance(sortedVec.begin(), it) << std::endl;
} // 输出: Found '7' at index: 6

int index = binarySearchIndex(sortedVec, 2);
if (index != -1) {
    std::cout << "Found '2' at index: " << index << std::endl; // 输出: Found '2' at index: 1
}

bool found = binarySearchBool(sortedVec, 15);
std::cout << "Is '15' in the vector? " << (found ? "Yes" : "No") << std::endl; // 输出: Is '15' in the vector? No

3. 哈希查找 (Hash Search)

思路: 使用 std::unordered_map 或 std::unordered_set 等哈希容器。

#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <functional>

// 通过预建的哈希表查找下标
template<typename T>
class IndexedHashMap {
private:
    std::unordered_map<T, int> valueToIndex;
public:
    IndexedHashMap(const std::vector<T>& vec) {
        for (int i = 0; i < vec.size(); ++i) {
            if (valueToIndex.find(vec[i]) == valueToIndex.end()) {
                valueToIndex[vec[i]] = i;
            }
        }
    }

    int findIndex(const T& target) const {
        auto it = valueToIndex.find(target);
        return (it != valueToIndex.end()) ? it->second : -1;
    }

    bool findBool(const T& target) const {
        return valueToIndex.find(target) != valueToIndex.end();
    }
};

示例用法:

std::vector<int> vec = {10, 20, 30, 40, 50};
IndexedHashMap<int> lookup(vec);

int index = lookup.findIndex(30);
if (index != -1) {
    std::cout << "Found '30' at index: " << index << std::endl; // 输出: Found '30' at index: 2
}

bool found = lookup.findBool(100);
std::cout << "Is '100' in the vector? " << (found ? "Yes" : "No") << std::endl; // 输出: Is '100' in the vector? No

4. 二叉搜索树查找 (BST)

思路: 在树结构中查找。

#include <memory>
#include <functional>
#include <optional>

template<typename T, typename Compare = std::less<T>>
class BinarySearchTreeWithIndex {
private:
    struct Node {
        T data;
        int index;
        std::unique_ptr<Node> left, right;
        Node(T val, int idx) : data(val), index(idx), left(nullptr), right(nullptr) {}
    };

    std::unique_ptr<Node> root;
    Compare comp;

    std::unique_ptr<Node> insertHelper(std::unique_ptr<Node> node, T val, int idx) {
        if (!node) return std::make_unique<Node>(val, idx);
        if (comp(val, node->data)) {
            node->left = insertHelper(std::move(node->left), val, idx);
        } else if (comp(node->data, val)) {
            node->right = insertHelper(std::move(node->right), val, idx);
        }
        return node;
    }

    std::optional<int> searchHelper(const Node* node, const T& target) const {
        if (!node) return std::nullopt;
        if (!comp(target, node->data) && !comp(node->data, target)) {
            return node->index;
        }
        if (comp(target, node->data)) {
            return searchHelper(node->left.get(), target);
        } else {
            return searchHelper(node->right.get(), target);
        }
    }

public:
    BinarySearchTreeWithIndex(Compare c = Compare{}) : comp(c) {}
    void insert(T val, int originalIndex) { root = insertHelper(std::move(root), val, originalIndex); }

    std::optional<int> searchIndex(const T& target) const {
        return searchHelper(root.get(), target);
    }

    bool searchBool(const T& target) const {
        return searchIndex(target).has_value();
    }
};

示例用法:

BinarySearchTreeWithIndex<int> bst;
bst.insert(5, 0); // 插入值5,原始下标为0
bst.insert(3, 1);
bst.insert(7, 2);

auto opt_index = bst.searchIndex(3);
if (opt_index.has_value()) {
    std::cout << "Found '3', original index was: " << opt_index.value() << std::endl; // 输出: Found '3', original index was: 1
}

bool found = bst.searchBool(8);
std::cout << "Is '8' in the tree? " << (found ? "Yes" : "No") << std::endl; // 输出: Is '8' in the tree? No

5. 斐波那契查找 (Fibonacci Search)

思路: 使用斐波那契数列来确定分割点。

#include <vector>
#include <functional>
#include <algorithm>

std::vector<int> generateFib(int n) {
    std::vector<int> fib = {0, 1};
    while (fib.back() < n) {
        fib.push_back(fib[fib.size()-1] + fib[fib.size()-2]);
    }
    return fib;
}

template<typename Container, typename T, typename Compare = std::less<typename Container::value_type>>
typename Container::const_iterator fibonacciSearch(const Container& sortedContainer, const T& target, Compare comp = Compare{}) {
    if (sortedContainer.empty()) return sortedContainer.end();
    int n = sortedContainer.size();
    auto fib = generateFib(n);
    int fibIndex = fib.size() - 1;
    int offset = -1;
    while (fib[fibIndex] > 1) {
        int i = std::min(offset + fib[fibIndex - 2], n - 1);
        if (comp(sortedContainer[i], target)) { fibIndex--; offset = i; }
        else if (comp(target, sortedContainer[i])) { fibIndex -= 2; }
        else { return sortedContainer.begin() + i; }
    }
    if (fib[1] && offset + 1 < n && !comp(target, sortedContainer[offset + 1]) && !comp(sortedContainer[offset + 1], target)) {
        return sortedContainer.begin() + offset + 1;
    }
    return sortedContainer.end();
}

template<typename T, typename Compare = std::less<T>>
int fibonacciSearchIndex(const std::vector<T>& sortedVec, const T& target, Compare comp = Compare{}) {
    int n = sortedVec.size();
    if (n == 0) return -1;
    auto fib = generateFib(n);
    int fibIndex = fib.size() - 1;
    int offset = -1;
    while (fib[fibIndex] > 1) {
        int i = std::min(offset + fib[fibIndex - 2], n - 1);
        if (comp(sortedVec[i], target)) { fibIndex--; offset = i; }
        else if (comp(target, sortedVec[i])) { fibIndex -= 2; }
        else { return i; }
    }
    if (fib[1] && offset + 1 < n && !comp(target, sortedVec[offset + 1]) && !comp(sortedVec[offset + 1], target)) {
        return offset + 1;
    }
    return -1;
}

template<typename Container, typename T, typename Compare = std::less<typename Container::value_type>>
bool fibonacciSearchBool(const Container& sortedContainer, const T& target, Compare comp = Compare{}) {
    return fibonacciSearch(sortedContainer, target, comp) != sortedContainer.end();
}

示例用法:

std::vector<int> sortedVec = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int index = fibonacciSearchIndex(sortedVec, 7);
if (index != -1) {
    std::cout << "Fibonacci Search: Found '7' at index: " << index << std::endl; // 输出: Fibonacci Search: Found '7' at index: 6
}
bool found = fibonacciSearchBool(sortedVec, 15);
std::cout << "Is '15' in the vector? " << (found ? "Yes" : "No") << std::endl; // 输出: Is '15' in the vector? No

6. 插值查找 (Interpolation Search)

思路: 预测目标值的位置。

#include <vector>
#include <functional>
#include <iterator>

template<typename RandomIt, typename T>
RandomIt interpolationSearch(RandomIt first, RandomIt last, const T& target) {
    if (first == last) return last;
    auto left = first; auto right = std::prev(last);
    using DiffType = typename std::iterator_traits<RandomIt>::difference_type;
    using ValueType = typename std::iterator_traits<RandomIt>::value_type;
    while (left <= right && target >= *left && target <= *right) {
        if (left == right) { if (*left == target) return left; return last; }
        if (*right == *left) break;
        DiffType pos = std::distance(first, left) +
                       static_cast<DiffType>(static_cast<double>(target - *left) / (*right - *left) * std::distance(left, right));
        auto mid_it = first + pos;
        if (*mid_it == target) { return mid_it; }
        else if (*mid_it < target) { left = std::next(mid_it); }
        else { right = std::prev(mid_it); }
    }
    return last;
}

template<typename T, typename Compare = std::less<T>>
int interpolationSearchIndex(const std::vector<T>& sortedVec, const T& target, Compare comp = Compare{}) {
    int left = 0, right = sortedVec.size() - 1;
    while (left <= right && comp(sortedVec[left], target) && comp(target, sortedVec[right])) {
        if (left == right) { return (sortedVec[left] == target) ? left : -1; }
        if (sortedVec[right] == sortedVec[left]) break;
        int pos = left + static_cast<int>(static_cast<double>(target - sortedVec[left]) / (sortedVec[right] - sortedVec[left]) * (right - left));
        if (sortedVec[pos] == target) { return pos; }
        else if (sortedVec[pos] < target) { left = pos + 1; }
        else { right = pos - 1; }
    }
    if (left <= right && sortedVec[left] == target) { return left; }
    return -1;
}

template<typename T, typename Compare = std::less<T>>
bool interpolationSearchBool(const std::vector<T>& sortedVec, const T& target, Compare comp = Compare{}) {
    return interpolationSearchIndex(sortedVec, target, comp) != -1;
}

示例用法:

std::vector<int> sortedVec = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
int index = interpolationSearchIndex(sortedVec, 13);
if (index != -1) {
    std::cout << "Interpolation Search: Found '13' at index: " << index << std::endl; // 输出: Interpolation Search: Found '13' at index: 6
}
bool found = interpolationSearchBool(sortedVec, 10);
std::cout << "Is '10' in the vector? " << (found ? "Yes" : "No") << std::endl; // 输出: Is '10' in the vector? No

7. 跳表 (Skip List)

思路: 通过多层索引来加速查找。

#include <vector>
#include <memory>
#include <random>
#include <functional>

template<typename T, typename Compare = std::less<T>>
class SkipList {
private:
    struct Node {
        T data; std::vector<Node*> forward; int originalIndex;
        Node(int level, T value, int idx) : data(value), forward(level + 1, nullptr), originalIndex(idx) {}
    };
    Compare comp; std::unique_ptr<Node> header; int maxLevel; mutable std::mt19937 gen; std::uniform_real_distribution<double> dis; const double p;
    int randomLevel() const { int level = 0; while (dis(gen) < p) { level++; } return level; }
public:
    explicit SkipList(double prob = 0.5, int seed = 19260817) : comp{}, maxLevel(0), gen(seed), dis(0.0, 1.0), p(prob) {
        header = std::make_unique<Node>(32, T{}, -1);
    }

    int findIndex(const T& target) const {
        Node* current = header.get();
        for (int i = maxLevel; i >= 0; i--) {
            while (current->forward[i] != nullptr && comp(current->forward[i]->data, target)) {
                current = current->forward[i];
            }
        }
        current = current->forward[0];
        if (current != nullptr && !comp(target, current->data) && !comp(current->data, target)) {
            return current->originalIndex;
        }
        return -1;
    }

    bool findBool(const T& target) const {
        return findIndex(target) != -1;
    }

    void insert(const T& value, int originalIndex) {
        std::vector<Node*> update(header->forward.size(), nullptr);
        Node* current = header.get();
        for (int i = maxLevel; i >= 0; i--) {
            while (current->forward[i] != nullptr && comp(current->forward[i]->data, value)) {
                current = current->forward[i];
            }
            update[i] = current;
        }
        current = current->forward[0];
        if (current != nullptr && !comp(value, current->data) && !comp(current->data, value)) { return; }
        int newLevel = randomLevel();
        if (newLevel > maxLevel) { for (int i = maxLevel + 1; i <= newLevel; i++) { update[i] = header.get(); } maxLevel = newLevel; }
        Node* newNode = new Node(newLevel, value, originalIndex);
        for (int i = 0; i <= newLevel; i++) { newNode->forward[i] = update[i]->forward[i]; update[i]->forward[i] = newNode; }
    }
};

示例用法:

SkipList<int> sl;
sl.insert(5, 0); // 插入值5,原始下标为0
sl.insert(3, 1);
sl.insert(7, 2);

int index = sl.findIndex(3);
if (index != -1) {
    std::cout << "Skip List: Found '3', original index was: " << index << std::endl; // 输出: Skip List: Found '3', original index was: 1
}

bool found = sl.findBool(8);
std::cout << "Is '8' in the skip list? " << (found ? "Yes" : "No") << std::endl; // 输出: Is '8' in the skip list? No

累活了