
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Floor of Every Element in Same Array in C++
In this problem, we are given an array arr[] of integer elements. Our task is to create a program to find the Floor of every element in the same array. If the floor of an element exists, we will print the floor otherwise print -1.
Floor of an element in array is the closest element which is smaller than or equal to the element in the array.
Let’s take an example to understand the problem
Input: arr[] = {3, 1, 5 ,7, 8, 2} Output: 2 -1 3 5 7 1
Solution Approach
An approach to solve the problem is by using nested loops. One to loop for each element of the array and the inner one for finding the floor of the element in the array.
Another approach to solve the problem is using an extra array to store the sorted array. Then loop over that original array and find the floor of the element in the sorted array using a binary seach algorithm.
Example
Program to illustrate the working of our solution
#include <bits/stdc++.h> using namespace std; void printFloorEle(int arr[], int n){ vector<int> sortedArr(arr, arr + n); sort(sortedArr.begin(), sortedArr.end()); for (int i = 0; i < n; i++) { if (arr[i] == sortedArr[0]) { if (arr[i] == sortedArr[1]) cout<<arr[i]; else cout<<-1; cout<<"\t"; continue; } auto iterator = lower_bound(sortedArr.begin(),sortedArr.end(), arr[i]); if (iterator != sortedArr.end() && *(iterator + 1) == arr[i]) cout<<arr[i]<<"\t"; else cout<<*(iterator - 1)<<"\t"; } } int main(){ int arr[] = { 3, 1, 5 ,7, 8, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout<<"The Floor of every element of the given array is "; printFloorEle(arr, n); return 0; }
Output
The Floor of every element of the given array is 2 -1 3 5 7 1