The dynamic search algorithm, also known as the "search-as-you-type" algorithm, is commonly used to implement features like autocomplete in search bars. This algorithm provides real-time suggestions based on the user's input and the available data.
How It Works
- Start with a dataset containing a list of items (e.g., words, names or products).
- As the user types each character, update the search query.
- Filter the dataset based on the current search query.
- Display the filtered results to the user in real-time.
Example
Consider a dataset of programming languages: ["C", "C++", "Java", "Python", "JavaScript", "Ruby", "Swift"].
- User types "C". Filtered results: ["C", "C++"].
- User types "C++". Filtered results: ["C++"].
- User types "Java". Filtered results: ["Java", "JavaScript"].
- User types "Py". Filtered results: ["Python"].
- User types "Jav". Filtered results: ["Java", "JavaScript"].
Example Code in C++
#include <iostream>
#include <vector>
#include <string>
std::vector<std::string> dynamicSearch(const std::vector<std::string>& dataset, const std::string& query) {
std::vector<std::string> results;
for (const std::string& item : dataset) {
if (item.find(query) != std::string::npos) {
results.push_back(item);
}
}
return results;
}
int main() {
std::vector<std::string> programmingLanguages = {"C", "C++", "Java", "Python", "JavaScript", "Ruby", "Swift"};
std::string userQuery = "Jav";
std::vector<std::string> suggestions = dynamicSearch(programmingLanguages, userQuery);
std::cout << "Suggestions for query '" << userQuery << "': ";
for (const std::string& suggestion : suggestions) {
std::cout << suggestion << " ";
}
std::cout << std::endl;
return 0;
}
In this example, the dynamicSearch
function takes a dataset of programming languages and a user query as inputs. It returns suggestions based on the current query. As the user types characters, the algorithm filters the dataset and displays real-time suggestions.
Note: The actual implementation of dynamic search can be more complex, involving techniques like trie structures or efficient indexing for large datasets.