Ceiling of every element in same array | C ++ implementation of efficient algorithm to find floor of every element ; Prints greater elements on left side of every element ; Create a sorted copy of arr [ ] ; Traverse through arr [ ] and do binary search for every element . ; Find the first element that is greater than the given element ; Since arr [ i ] also exists in array , * ( it - 1 ) will be same as arr [ i ] . Let us check * ( it - 2 ) is also same as arr [ i ] . If true , then arr [ i ] exists twice in array , so ceiling is same same as arr [ i ] ; If next element is also same , then there are multiple occurrences , so print it ; Driver program to test insertion sort
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printPrevGreater ( int arr [ ] , int n ) { if ( n == 1 ) { cout << " - 1" ; return ; } vector < int > v ( arr , arr + n ) ; sort ( v . begin ( ) , v . end ( ) ) ; for ( int i = 0 ; i < n ; i ++ ) { auto it = upper_bound ( v . begin ( ) , v . end ( ) , arr [ i ] ) ; if ( ( it - 1 ) != v . begin ( ) && * ( it - 2 ) == arr [ i ] ) { cout << arr [ i ] << " ▁ " ; } else if ( it != v . end ( ) ) cout << * it << " ▁ " ; else cout << -1 << " ▁ " ; } } int main ( ) { int arr [ ] = { 10 , 5 , 11 , 10 , 20 , 12 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printPrevGreater ( arr , n ) ; return 0 ; }