Add

Floor and ceil of an element in an array using C++



Floor and ceil of an element in an array using c++

#include <bits/stdc++.h>

using namespace std;

//print ceil & floor for the number

void ceilandfloorLinear(vector<int>& arr, int k)

{

    cout << "..............Using linear search......\n";

    //find the closest greater than number & closet lesser number

    int _ceil = INT_MAX;

    int _floor = INT_MIN;

    for (int i = 0; i < arr.size(); i++) {

        if (arr[i] > k && _ceil > arr[i])

            _ceil = arr[i];

        if (arr[i] < k && _floor < arr[i])

            _floor = arr[i];

    }

    if (_ceil != INT_MAX)

        cout << "ceiling of " << k << " is: " << _ceil << "\n";

    else

        cout << "There is no ceiling of " << k << "\n";

    if (_floor != INT_MIN)

        cout << "floor of " << k << " is: " << _floor << "\n";

    else

        cout << "There is no floor of " << k << "\n";

}

void ceilandfloorBinary(vector<int>& arr, int k)

{

    cout << "..............Using binary search......\n";

    //find the closest greater than number & closet lesser number

    int _ceil = INT_MAX;

    int _floor = INT_MIN;

    sort(arr.begin(), arr.end());

    int low = 0, high = arr.size() - 1;

    while (low <= high) {

        int mid = (high - low) / 2 + low;

        if (arr[mid] == k) {

            _ceil = k;

            _floor = k;

            break;

        }

        else if (arr[mid] > k) {

            _ceil = arr[mid];

            high = mid - 1;

        }

        else {

            _floor = arr[mid];

            low = mid + 1;

        }

    }

    if (_ceil != INT_MAX)

        cout << "ceiling of " << k << " is: " << _ceil << "\n";

    else

        cout << "There is no ceiling of " << k << "\n";

    if (_floor != INT_MIN)

        cout << "floor of " << k << " is: " << _floor << "\n";

    else

        cout << "There is no floor of " << k << "\n";

}

int main()

{

    cout << "Enter number of elements\n";

    int n;

    cin >> n;

    vector<int> arr(n);

    cout << "Enter the elements\n";

    for (int i = 0; i < n; i++)

        cin >> arr[i];

    cout << "Enter the number for which you need ceil & floor\n";

    int k;

    cin >> k;

    //using linear search

    ceilandfloorLinear(arr, k);

    //using binary search

    ceilandfloorBinary(arr, k);

    return 0;

}

Output:

..............Using binary search......

7

Enter the elements

56

32

87

66

12

59

33

Enter the number for which you need ceil & floor

20

..............Using linear search......

ceiling of 20 is: 32

floor of 20 is: 12

ceiling of 20 is: 32

floor of 20 is: 12


Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.