|
| 1 | +/** |
| 2 | + * @file test_binary_search.cpp |
| 3 | + * @brief Unit tests for the binary search algorithm. |
| 4 | + */ |
| 5 | + |
| 6 | +#include "binary_search.h" |
| 7 | +#include "gtest/gtest.h" |
| 8 | + |
| 9 | +/// @brief Test searching an empty array. |
| 10 | +TEST(BinarySearchTest, EmptyArray) { |
| 11 | + std::vector<int> arr; |
| 12 | + EXPECT_EQ(binary_search(arr, 5), std::nullopt); |
| 13 | +} |
| 14 | + |
| 15 | +/// @brief Test finding the only element in a single-element array. |
| 16 | +TEST(BinarySearchTest, SingleElementFound) { |
| 17 | + std::vector<int> arr{5}; |
| 18 | + EXPECT_EQ(binary_search(arr, 5), 0); |
| 19 | +} |
| 20 | + |
| 21 | +/// @brief Test not finding element in a single-element array. |
| 22 | +TEST(BinarySearchTest, SingleElementNotFound) { |
| 23 | + std::vector<int> arr{5}; |
| 24 | + EXPECT_EQ(binary_search(arr, 3), std::nullopt); |
| 25 | +} |
| 26 | + |
| 27 | +/// @brief Test target at the first position. |
| 28 | +TEST(BinarySearchTest, TargetAtBeginning) { |
| 29 | + std::vector<int> arr{1, 2, 3, 4, 5}; |
| 30 | + EXPECT_EQ(binary_search(arr, 1), 0); |
| 31 | +} |
| 32 | + |
| 33 | +/// @brief Test target at the last position. |
| 34 | +TEST(BinarySearchTest, TargetAtEnd) { |
| 35 | + std::vector<int> arr{1, 2, 3, 4, 5}; |
| 36 | + EXPECT_EQ(binary_search(arr, 5), 4); |
| 37 | +} |
| 38 | + |
| 39 | +/// @brief Test target in the middle of the array. |
| 40 | +TEST(BinarySearchTest, TargetInMiddle) { |
| 41 | + std::vector<int> arr{1, 2, 3, 4, 5}; |
| 42 | + EXPECT_EQ(binary_search(arr, 3), 2); |
| 43 | +} |
| 44 | + |
| 45 | +/// @brief Test target smaller than all elements. |
| 46 | +TEST(BinarySearchTest, TargetTooSmall) { |
| 47 | + std::vector<int> arr{2, 4, 6, 8, 10}; |
| 48 | + EXPECT_EQ(binary_search(arr, 1), std::nullopt); |
| 49 | +} |
| 50 | + |
| 51 | +/// @brief Test target larger than all elements. |
| 52 | +TEST(BinarySearchTest, TargetTooLarge) { |
| 53 | + std::vector<int> arr{2, 4, 6, 8, 10}; |
| 54 | + EXPECT_EQ(binary_search(arr, 12), std::nullopt); |
| 55 | +} |
| 56 | + |
| 57 | +/// @brief Test target in gap between elements. |
| 58 | +TEST(BinarySearchTest, TargetInGap) { |
| 59 | + std::vector<int> arr{2, 4, 6, 8, 10}; |
| 60 | + EXPECT_EQ(binary_search(arr, 5), std::nullopt); |
| 61 | +} |
| 62 | + |
| 63 | +/// @brief Test searching with negative numbers. |
| 64 | +TEST(BinarySearchTest, WithNegativeNumbers) { |
| 65 | + std::vector<int> arr{-10, -5, 0, 5, 10}; |
| 66 | + EXPECT_EQ(binary_search(arr, -5), 1); |
| 67 | +} |
0 commit comments