Find largest element from array without using conditional operator in C++


Suppose we have an array A with some elements. We have to find the largest element in the array A, but the constraint is, we cannot use any conditional operator. So if A = [12, 63, 32, 24, 78, 56, 20], then maximum element will be 78.

To solve this problem, we will use the bitwise AND operation. at first we will insert one extra element INT_MAX (where all bit is 1) in array. Then we will try to find maximum AND value of any pair from the array. This obtained max value will contain AND value of INT_MAX and largest element of the original array, and this will be the result.

Example

#include <iostream>
#include <vector>
using namespace std;
int 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;
   }
   int findLargestElement(int arr[], int n) {
      vector<int> elements_vector(arr, arr + n);
      elements_vector.push_back(INT_MAX);
      n++;
      int res = 0;
      for (int bit = 31; bit >= 0; bit--) {
         int count = checkBit(res | (1 << bit), elements_vector, n);
         if ((count | 1) != 1)
               res |= (1 << bit);
      }
      return res;
}
int main() {
   int arr[] = {12, 63, 32, 24, 78, 56, 20};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Largest element is: " << findLargestElement(arr, n);
}

Output

Largest element is: 78

Updated on: 01-Nov-2019

177 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements