#include <iostream>
#include <vector>
#include <optional>
using namespace std;
// Function to find floor and ceil in sorted array
pair<optional<int>, optional<int>> floorAndCeil(const vector<int>& arr, int target) {
int low = 0, high = (int)arr.size() - 1;
optional<int> floorVal = nullopt;
optional<int> ceilVal = nullopt;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target) {
// Exact match is both floor and ceil
return {arr[mid], arr[mid]};
} else if (arr[mid] < target) {
floorVal = arr[mid]; // arr[mid] could be floor
low = mid + 1; // search right side for closer floor
} else {
ceilVal = arr[mid]; // arr[mid] could be ceil
high = mid - 1; // search left side for closer ceil
}
}
return {floorVal, ceilVal};
}
int main() {
vector<int> arr = {1, 3, 5, 7, 9};
int target = 6;
auto [floorVal, ceilVal] = floorAndCeil(arr, target);
cout << "Floor = ";
if (floorVal.has_value()) cout << floorVal.value() << "\n";
else cout << "None\n";
cout << "Ceil = ";
if (ceilVal.has_value()) cout << ceilVal.value() << "\n";
else cout << "None\n";
return 0;
}
loop until search space is exhausted
int mid = low + (high - low) / 2;
calculate middle index to split search space
if (arr[mid] == target) { return {arr[mid], arr[mid]}; }
exact match found, floor and ceil are target
else if (arr[mid] < target) { floorVal = arr[mid]; low = mid + 1; }
arr[mid] less than target, update floor and search right side
else { ceilVal = arr[mid]; high = mid - 1; }
arr[mid] greater than target, update ceil and search left side