Find all array elements occurring more than âŒŠN / 3 âŒ ‹ times | Function to find Majority element in an array ; if this element is previously seen , increment count1 . ; if this element is previously seen , increment count2 . ; if current element is different from both the previously seen variables , decrement both the counts . ; Again traverse the array and find the actual counts . ; Driver code
function findMajority ( arr , n ) { var count1 = 0 , count2 = 0 ; var first = 2147483647 , second = 2147483647 ; = var flag = 0 ; for ( var i = 0 ; i < n ; i ++ ) { if ( first === arr [ i ] ) count1 ++ ; else if ( second === arr [ i ] ) count2 ++ ; else if ( count1 === 0 ) { count1 ++ ; first = arr [ i ] ; } else if ( count2 === 0 ) { count2 ++ ; second = arr [ i ] ; } else { count1 -- ; count2 -- ; } } count1 = 0 ; count2 = 0 ; for ( var i = 0 ; i < n ; i ++ ) { if ( arr [ i ] === first ) count1 ++ ; else if ( arr [ i ] === second ) count2 ++ ; } if ( count1 > n / 3 ) { document . write ( first + " " ) ; flag = 1 ; } if ( count2 > n / 3 ) { document . write ( second + " " ) ; flag = 1 ; } if ( flag === 0 ) { document . write ( " " + " " ) ; } } var arr = [ 2 , 2 , 3 , 1 , 3 , 2 , 1 , 1 ] ; var n = arr . length ; findMajority ( arr , n ) ;