Find smallest and largest element from 2d array

Find the smallest and largest element and its position from the 2D array.

Example 1:

Input : {{6, 4, 2, 4}, {5, 6, 9, 2}, {5, 7, 2, 1}};
Output: Largest element 9 at (1,2)
        Smalast element 1 at (2,3)
Approach: 

Java

public class FIndSmallestAndLargestArray {
    static int smallElm = 0;
    static int smallI = 0;
    static int smallJ = 0;
    static int largElm = 0;
    static int largElmI = 0;    
    static int largElmJ = 0;

    public static void main(String[] args) {
        int a[][] = { { 6424 }, { 5692 },
                 { 5721 } };
        searchingElement(a);
        System.out.println("Largest element " + largElm 
            + " at (" + largElmI + "," + largElmJ + ")");
        System.out.println("Smalast element " + smallElm 
             + " at (" + smallI + "," + smallJ + ")");
    }

    // method two find smallest and largest element
    public static void searchingElement(int[][] a) {
        int m = 0;
        // iterate till row end
        for (int i = 0; i < a.length; i++) {
            // iterate till col end
            for (int j = 0; j < a[0].length; j++) {
                if (i == 0) {
                    smallElm = a[i][j];
                    smallI = i;
                    smallJ = j;
                    largElm = a[i][j];
                    largElmI = i;
                    largElmJ = j;
                }
                m = a[i][j];
                // for find smallest element
                if (smallElm > m) {
                    smallElm = a[i][j];
                    smallI = i;
                    smallJ = j;
                }
                // for find greatest element
                if (largElm < m) {
                    largElm = a[i][j];
                    largElmI = i;
                    largElmJ = j;
                }

            }
        }
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

int largElm=INT_MIN,largElmI=0,largElmJ=0;
int smallElm=INT_MAX,smallI=0,smallJ=0;
void searchingElement(vector<vector<int>> &arr)
{
    int m=0;
    int n=arr.size();
    if(n!=0)
      m=arr[0].size();
    for(int i=0;i<n;i++)
      {
          for(int j=0;j<m;j++)
           {
               if(arr[i][j]>largElm)
                 {
                     largElm=arr[i][j];
                     largElmI=i;
                     largElmJ=j;
                 }
                if(arr[i][j]<smallElm)
                 {
                     smallElm=arr[i][j];
                     smallI=i;
                     smallJ=j;
                 }
           }

      }
    
}
int main()
{
    vector<vector<int>> arr= { { 6424 }, { 5692 },
                 { 5721 } };
    searchingElement(arr);
    cout<<"Largest element "<<largElm;
    cout<< " at ("<<largElmI<<","<<largElmJ<<")"<<"\n";
    cout<<"Smalast element "<<smallElm; 
    cout<<" at ("<<smallI<<","<<smallJ<<")";
}


No comments:

Post a Comment