Find elements larger than half of the elements in an array | Set 2 | C ++ program for the above approach ; Function to find the element that are larger than half of elements of the array ; Find the value of mid ; Stores the maximum element ; Stores the frequency of each array element ; Traverse the array in the reverse order ; Decrement the value of count [ i ] and mid ; Print the current element ; Check if the value of mid is equal to 0 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findLarger ( int arr [ ] , int n ) { int mid = ( n + 1 ) / 2 ; int mx = * max_element ( arr , arr + n ) ; int count [ mx + 1 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { count [ arr [ i ] ] ++ ; } for ( int i = mx ; i >= 0 ; i -- ) { while ( count [ i ] > 0 ) { count [ i ] -- ; mid -- ; cout << i << ' ▁ ' ; if ( mid == 0 ) break ; } if ( mid == 0 ) break ; } } int main ( ) { int arr [ ] = { 10 , 4 , 2 , 8 , 9 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findLarger ( arr , N ) ; return 0 ; }