Find minimum in an array without using Relational Operators

Given an array A[] of non-negative integers, find the minimum in the array without using Relational Operators.

Examples:

Input : A[] = {2, 3, 1, 4, 5}
Output : 1

Input : A[] = {23, 17, 93}
Output : 17

We use repeated subtraction to find out the minimum. To find minimum between two numbers, we take a variable counter initialized to zero. We keep decreasing the both the value till any one of them becomes equal to zero, increasing the counter simultaneously. The minimum value reaches zero first and the counter has increased to be the minimum of both of them. We first find the minimum of first two numbers and then compare it with the rest elements of the array one by one to find the overall minimum.

Below is the implementation of the above idea.

#include <iostream>
using namespace std;
// Function to find minimum between two non-negative
// numbers without using relational operator.
int minimum(int x, int y)
{
    int c = 0;
    // Continues till any element becomes zero.
    while (x && y)
    {
        x--;
        y--;
        c++;
    }
    return c;
}
// Function to find minimum in an array.
int arrayMinimum(int A[], int N)
{
    // calculating minimum of first two numbers
    int mn = A[0];
    // Iterating through each of the member of
    // the array to calculate the minimum
    for (int i = N-1; i; i--)
        // Finding the minimum between current
        // minimum and current value.
        mn = minimum(mn, A[i]);   
    return mn;
}
// Driver code
int main()
{
    int A[] = { 2, 3, 1, 4 };
    int N = sizeof(A) / sizeof(A[0]);
    cout << arrayMinimum(A, N);
    return 0;
}

Output:

1

The time complexity of the code will be O(N*max) where max is the maximum of the array elements.

Limitations : This will only work if the array contains all non negative integers.

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:http://www.geeksforgeeks.org/find-minimum-array-without-using-relational-operators/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

rakesh

Leave a Reply

Your email address will not be published. Required fields are marked *

Skip to toolbar