15 June 2018

Smallest greater elements in whole array


nput :  6 3 9 8 10 2 1 15 7 
Output : 7 6 10 9 15 3 2 _ 8
Here every element of array has next greater 
element but at index 7,
15 is the greatest element of given array
and no other element is greater from 15 
so at the index of 15 we fill with '_' .

Input  : 13 6 7 12
Output : _ 7 12 13
Here, at index 0, 13 is the greatest 
value in given array and no other 
array element is greater from 13 so
at index 0 we fill '_'.

public class NewClass32 {
   
    void nextgreatest(int ar[])
    {   
        for(int i=0;i<ar.length;i++)
        {  
            int max=Integer.MAX_VALUE,c=0;   
           
            for(int j=0;j<ar.length;j++)
            {
              
                if(ar[i]<ar[j] && ar[j]<max)
                {  max=ar[j]; c=1; }
               
            }
            if(c==1)
                System.out.print(max+" ");
             else
                System.out.print("_ ");
        }
    }

    public static void main(String args[])
    {
        int ar[]={6,3,9,8,10,2,1,15,7};
        NewClass32 ob=new NewClass32();
        ob.nextgreatest(ar);
    }
}

No comments:

Post a Comment