Find largest element from array without using conditional operator - GeeksforGeeks

19 Nov, 2021
Given an array of n-elements, we have to find the largest element among them without using any conditional operator like greater than or less than.Examples:  
Input : arr[] = {5, 7, 2, 9}
Output : Largest element = 9

Input : arr[] = {15, 0, 2, 15}
Output : Largest element = 15
 
First Approach (Use of Hashing) : To find the largest element from the array we may use the concept the of hashing where we should maintain a hash table of all element and then after processing all array element we should find the largest element in hash by simply traversing the hash table from end. But there are some drawbacks of this approach like in case of very large elements maintaining a hash table is either not possible or not feasible.Better Approach (Use of Bitwise AND) : Recently we have learn how to find the largest AND value pair from a given array. Also, we know that if we take bitwise AND of any number with INT_MAX (whose all bits are set bits) then the result will be that number itself. Now, using this property we will try to find the largest element from the array without any use conditional operator like greater than or less than.For finding the largest element we will first insert an extra element i.e. INT_MAX in array, and after that we will try to find the maximum AND value of any pair from the array. This obtained maximum value will contain AND value of INT_MAX and largest element of original array and is our required result.Below is the implementation of above approach :  
C++
Java
Python3
C#
PHP
Javascript
// C++ Program to find largest element from array#include <bits/stdc++.h>using namespace std; // Utility function to check number of// elements having set msb as of patternint checkBit(int pattern, vector<int> arr, int n){    int count = 0;    for (int i = 0; i < n; i++)        if ((pattern & arr[i]) == pattern)            count++;    return count;} // Function for finding maximum and value pairint largest(int arr[], int n){    // Create a vector of given array    vector<int> v(arr, arr + n);     // Insert INT_MAX and update n    v.push_back(INT_MAX);    n++;     int res = 0;     // Iterate over total of 30bits from    // msb to lsb    for (int bit = 31; bit >= 0; bit--)    {         // Find the count of element having set msb        int count = checkBit(res | (1 << bit), v, n);         // if count | 1 != 1 set particular        // bit in result        if ((count | 1) != 1)            res |= (1 << bit);    }     return res;} // Driver Codeint main(){    int arr[] = { 4, 8, 6, 2 };    int n = sizeof(arr) / sizeof(arr[0]);    cout << "Largest element = " << largest(arr, n);    return 0;}
// Java Program to find largest element from arrayimport java.util.Vector;import java.util.Arrays; class GfG{ // Utility function to check number of// elements having set msb as of patternstatic int checkBit(int pattern, Vector<Integer> arr, int n){    int count = 0;    for (int i = 0; i < n; i++)        if ((pattern & arr.get(i)) == pattern)            count++;    return count;} // Function for finding maximum and value pairstatic int largest(int arr[], int n){    // Create a vector of given array    Vector<Integer> v = new Vector<>();    for(Integer a:arr)        v.add(a);     // Insert INT_MAX and update n    v.add(Integer.MAX_VALUE);    n++;     int res = 0;     // Iterate over total of 30bits from    // msb to lsb    for (int bit = 31; bit >= 0; bit--)    {         // Find the count of element having set msb        int count = checkBit(res | (1 << bit), v, n);         // if count | 1 != 1 set particular        // bit in result        if ((count | 1) != 1)            res |= (1 << bit);    }     return res;} // Driver Codepublic static void main(String[] args){    int arr[] = { 4, 8, 6, 2 };    int n = arr.length;    System.out.println("Largest element = " +                            largest(arr, n));}} /* This code contributed by PrinciRaj1992 */
# Python3 Program to find largest# element from arrayimport math as mt # Utility function to check number of# elements having set msb as of patterndef checkBit(pattern, arr, n):    count = 0    for i in range(n):        if ((pattern & arr[i]) == pattern):            count += 1    return count # Function for finding maximum# and value pairdef largest(arr, n):     # Create a vector of given array    v = arr     # Insert max value of Int and update n    v.append(2**31 - 1)    n = n + 1     res = 0     # Iterate over total of 30bits    # from msb to lsb    for bit in range(31, -1, -1):         # Find the count of element        # having set msb        count = checkBit(res | (1 << bit), v, n)         # if count | 1 != 1 set particular        # bit in result        if ((count | 1) != 1):            res |= (1 << bit)         return res # Driver Codearr = [4, 8, 6, 2]n = len(arr)print("Largest element =", largest(arr, n)) # This code is contributed by# Mohit kumar 29
// C# Program to find largest element from arrayusing System;   using System.Collections.Generic;    class GfG{  // Utility function to check number of// elements having set msb as of patternstatic int checkBit(int pattern, List<int> arr, int n){    int count = 0;    for (int i = 0; i < n; i++)        if ((pattern & arr[i]) == pattern)            count++;    return count;}  // Function for finding maximum and value pairstatic int largest(int []arr, int n){    // Create a vector of given array    List<int> v = new List<int>();    foreach(int a in arr)        v.Add(a);      // Insert INT_MAX and update n    v.Add(int.MaxValue);    n++;      int res = 0;      // Iterate over total of 30bits from    // msb to lsb    for (int bit = 31; bit >= 0; bit--)    {          // Find the count of element having set msb        int count = checkBit(res | (1 << bit), v, n);          // if count | 1 != 1 set particular        // bit in result        if ((count | 1) != 1)            res |= (1 << bit);    }      return res;}  // Driver Codepublic static void Main(String[] args){    int []arr = { 4, 8, 6, 2 };    int n = arr.Length;    Console.WriteLine("Largest element = " +                            largest(arr, n));}} // This code contributed by Rajput-Ji
<?php// php Program to find largest// element from array // Utility function to check// number of elements having// set msb as of patternfunction checkBit($pattern,$arr,$n){    $count = 0;    for ($i = 0; $i < $n; $i++)        if (($pattern & $arr[$i]) == $pattern)            $count++;    return $count;} // Function for finding// maximum and value pairfunction largest($arr, $n){    $res = 0;     // Iterate over total of    // 30bits from msb to lsb    for ($bit = 31; $bit >= 0; $bit--)    {         // Find the count of element        // having set msb        $count = checkBit($res | (1 << $bit),$arr, $n);         // if count | 1 != 1 set        // particular bit in result        if ($count | 1 != 1)            $res |= (1 << $bit);    }     return $res;}     // Driver code    $arr = array( 4, 8, 6, 2 );    $n = sizeof($arr) / sizeof($arr[0]);    echo "Largest element = ". largest($arr, $n); // This code is contributed by mits ?>
<script>// javascript Program to find largest element from array  // Utility function to check number of// elements having set msb as of patternfunction checkBit( pattern, arr, n){    let count = 0;    for (let i = 0; i < n; i++)        if ((pattern & arr[i]) == pattern)            count++;    return count;} // Function for finding maximum and value pairfunction largest( arr, n){    // Create a vector of given array    let v = [];    for(let i = 0;i<n;i++){        v.push(arr[i])    }    // Insert INT_MAX and update n    v.push(Math.pow(2,31)-1);    n++;     let res = 0;     // Iterate over total of 30bits from    // msb to lsb    for (let bit = 31; bit >= 0; bit--)    {         // Find the count of element having set msb        let count = checkBit(res | (1 << bit), v, n);         // if count | 1 != 1 set particular        // bit in result        if ((count | 1) != 1)            res |= (1 << bit);    }         return res;} let a = [ 4, 8, 6, 2 ];n = a.length;document.write("Largest element = ");document.write(largest(a, n)); // This code is contributed by rohitsingh07052.</script>
Output:  
Largest element = 8
Time Complexity: O(32)
Auxiliary Space: O(N) 
Mithun Kumar
mohit kumar 29
princiraj1992
Rajput-Ji
rohitsingh07052
Arrays
Bit Magic
Arrays
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Cyclic Redundancy Check and Modulo-2 Division
Count set bits in an integer