Array Question 15

Home / Java Practice Question / Array Question 15

Array Question 15


Question 15. Write a Program to find peak element in array.

                           An element is called a peak element if its value is not smaller than the value of its adjacent elements(if they exists).

Program


class Solution

{

public int peakElement(int[] arr,int n)

    {

       if(n==1){

           return 0;

       }       

       if(arr[0]>arr[1]){

           return 0;

       }  

       if(arr[n-1]>arr[n-2]){

           return n-1;

       }

       int res=0;

       for(int i=1;i<arr.length-1;i++){

           if(arr[i]>arr[i-1] && arr[i]>=arr[i+1]){  

               res=i;

               break;

           }

       }

      return res;

    }

}