From 0a057c12f1df3332416a59a8ec97114f5a3c8933 Mon Sep 17 00:00:00 2001 From: noctera Date: Sat, 18 Dec 2021 11:20:14 +0100 Subject: [PATCH] feat: implementation of linear search --- .../algorithms/search/linearSearch.hpp | 16 ++++++++++++++ .../AlgoCpp/algorithms/sorting/bubbleSort.hpp | 3 +-- tests/CMakeLists.txt | 1 + tests/search/linearSearch.cpp | 21 +++++++++++++++++++ 4 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 tests/search/linearSearch.cpp diff --git a/include/AlgoCpp/algorithms/search/linearSearch.hpp b/include/AlgoCpp/algorithms/search/linearSearch.hpp index e69de29..9e12c1e 100644 --- a/include/AlgoCpp/algorithms/search/linearSearch.hpp +++ b/include/AlgoCpp/algorithms/search/linearSearch.hpp @@ -0,0 +1,16 @@ +#pragma once + +namespace algocpp { +namespace search { + +template +bool linearSearch(T& input, Z item) { + for (auto it = input.begin(); it != input.end(); ++it) { + if (*it == item) { + return true; + } + } + return false; +} +} // namespace search +} // namespace algocpp \ No newline at end of file diff --git a/include/AlgoCpp/algorithms/sorting/bubbleSort.hpp b/include/AlgoCpp/algorithms/sorting/bubbleSort.hpp index 4089f3c..84ff99c 100644 --- a/include/AlgoCpp/algorithms/sorting/bubbleSort.hpp +++ b/include/AlgoCpp/algorithms/sorting/bubbleSort.hpp @@ -1,7 +1,6 @@ #pragma once -#include -#include +#include namespace algocpp { namespace sorting { diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 39d3d57..4aedc2d 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -10,6 +10,7 @@ add_executable( ${PROJECT_NAME} "main.cpp" "sorting/bubbleSort.cpp" + "search/linearSearch.cpp" ${BenchmarkFiles} ) diff --git a/tests/search/linearSearch.cpp b/tests/search/linearSearch.cpp new file mode 100644 index 0000000..599ee94 --- /dev/null +++ b/tests/search/linearSearch.cpp @@ -0,0 +1,21 @@ +#define CATCH_CONFIG_ENABLE_BENCHMARKING +#include "AlgoCpp/algorithms/search/linearSearch.hpp" +#include +#include +#include +#include + +using namespace algocpp::search; + +TEST_CASE("Check if linear search is working", "[linearSearch]") { + std::vector test1 = {1, 4, 5, 2, 3}; + std::vector test2 = {1}; + std::vector test3 = {'c', 'b', 'x', 'm', 'n'}; + + REQUIRE(linearSearch(test1, 5) == true); + REQUIRE(linearSearch(test1, 7) == false); + REQUIRE(linearSearch(test2, 1) == true); + REQUIRE(linearSearch(test2, 5) == false); + REQUIRE(linearSearch(test3, 'b') == true); + REQUIRE(linearSearch(test3, 'A') == false); +}