Junior — Middle
How do B-trees and hash indexes differ in the context of data organization and their search?
sobes.tech AI
Answer from AI
Hash table is a data structure that stores key-value pairs and provides very fast access to data by key, usually close to O(1) time.
Principle of operation:
- The key is transformed into an array index using a hash function.
- The value or a list of values (in case of collisions) is stored at this index.
- In case of collisions (different keys producing the same index), collision resolution methods like chaining (linked list) or open addressing are used.
Differences from other key-value structures:
- Unlike balanced trees (e.g., std::map in C++), hash tables are typically faster for search, insert, and delete, but do not guarantee element order.
- Unlike arrays or lists, where search by key requires iteration, hash tables provide direct access.
Example in C++ using std::unordered_map:
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> map;
map["apple"] = 5;
map["banana"] = 3;
std::cout << "apple: " << map["apple"] << std::endl; // Outputs 5
return 0;
}