Find maximum in an array without using Relational Operators in C++


In this problem, we are given an array arr[] of size n consisting of positive values. Our task is to find maximum in an array without using Relational Operators. 

Let’s take an example to understand the problem,

Input: arr[] = {5, 1, 6, 7 , 8, 2}

Output: 8

Solution Approach

Since we need to compare values without using logical operators. For this we need to perform repeated subtraction, the number which will last longer will be the larger one.

We will decrement all values by one till they become zero. We will start with the first two values of the array and find the greatest of both. Then we need to compare the rest of array values with the largest element of the array. Using this we will find the maximum of all elements. 

Program to illustrate the working of our solution,

Example

Live Demo

#include <iostream>
using namespace std;

int returnMax(int x, int y) {
   
   int c = 0;

   while(x || y)
   {
      if(x)
         x--;
      if(y)
         y--;
      c++;
   }
   return c;
}

int findMaxEle(int A[], int N) {

   int maxVal = A[0];
   
   for (int i = N-1; i; i--)
      maxVal = returnMax(maxVal, A[i]);
   
   return maxVal;
}

int main() {
   
   int A[] = {5, 1, 6, 7 , 8, 2};
   int N = sizeof(A) / sizeof(A[0]);
   cout<<"The maximum element of the array is "<<findMaxEle(A, N);
   return 0;
}

Output

The maximum element of the array is 8>

Updated on: 25-Jan-2021

158 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements