Search code examples
sortingmatrixmaxrowsminimum

minimum of all rows maximum in matrix


I have to find the minimum of every row's maximum in matrix. And then print the row which contains that element. Why it cannot be done like this ?

for(i=0; i<m; i++)
    {
        for(j=0; j<n; j++)
        {
            if(a[i][j]>max)
                max=a[i][j];

        }
        if(min>max){
            min=max;
            p=i;
        }
    }

Solution

  • You need to reset max for each row:

    for(i=0; i<m; i++)
        {
            max = 0;  // or some value less than the minimum value in the matrix
    
            for(j=0; j<n; j++)
            {
                if(a[i][j]>max)
                    max=a[i][j];
    
            } 
            if(min>max){
                min=max;
                p=i;
            }
        }
    

    Otherwise, once max has replaced min once, a value can never be both greater than max and less than min.