Skip to content

Commit

Permalink
added some search algorithms
Browse files Browse the repository at this point in the history
  • Loading branch information
spirosmaggioros committed Feb 3, 2024
1 parent 630c6ac commit 53600c4
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/algorithms/searching/exponential_search.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#ifndef EXPONENTIAL_SEARCH_H
#define EXPONENTIAL_SEARCH_H

#ifdef __cplusplus
#include "binary_search.h"
#include <iostream>
#endif

template <typename T> int64_t exponential_search(std::vector<T> arr, T key) {
if (arr[0] == key) {
return true;
}
int64_t i = 1, n = arr.size();
while (i < n && arr[i] < key) {
i *= 2;
}
int64_t lo = i / 2, hi = std::min(i, n - 1);
while (lo <= hi) {
int64_t mid = (lo + hi) / 2;
if (arr[mid] == key) {
return mid;
} else if (arr[mid] < key) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return -1;
}

#endif
17 changes: 17 additions & 0 deletions src/algorithms/searching/linear_search.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#ifndef LINEAR_SEARCH_H
#define LINEAR_SEARCH_H

#ifdef __cplusplus
#include <iostream>
#endif

template <typename T> bool linear_search(std::vector<T> arr, T key) {
for (T &x : arr) {
if (x == key) {
return true;
}
}
return false;
}

#endif
10 changes: 10 additions & 0 deletions tests/algorithms/searching/exponential_search.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#define CATCH_CONFIG_MAIN
#include "../../../src/algorithms/searching/exponential_search.h"
#include "../../catch2/catch.hpp"

TEST_CASE("testing exponential search") {
std::vector<int> v = {1, 6, 43, 0, 9, 20, 60};
REQUIRE(exponential_search(v, 6) == 1);
REQUIRE(exponential_search(v, 60) == 6);
REQUIRE(exponential_search(v, -10) == -1);
}
9 changes: 9 additions & 0 deletions tests/algorithms/searching/linear_search.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#define CATCH_CONFIG_MAIN
#include "../../../src/algorithms/searching/linear_search.h"
#include "../../catch2/catch.hpp"

TEST_CASE("testing linear search") {
std::vector<int> v = {1, 5, 3, 1, 2, 3, -41, -20};
REQUIRE(linear_search(v, 5) == true);
REQUIRE(linear_search(v, -40) == false);
}

0 comments on commit 53600c4

Please sign in to comment.