# Java Program to Find the Peak Element of an Array O(n) time (Naive Method)

«
»
This is a Java Program to find peak element of an array. A peak element of an array is that element which is not smaller than its neighbors. Consider only one neighbour for corner elements. The time complexity of the following program is O (n).

Brute Force Algorithm is as follows :

```for i in range (n) :
if A[i - 1] <= A[i] >= A[i + 1] :
print A[i]
end if
end for```

Here is the source code of the Java program to find peak element of an array. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

1. `/*`
2. ` *    Java Program to Find the peak element of an array O(n) time (Naive Method)`
3. ` */`
4. ` `
5. `import java.util.Scanner;`
6. ` `
7. `public class PeakElement1`
8. `{`
9. `    public static void main(String[] args)`
10. `    {    `
11. `        Scanner scan = new Scanner(System.in);`
12. `        System.out.println("Enter size of array");`
13. `        int N = scan.nextInt();`
14. `        int[] arr = new int[N + 2];`
15. `        /* set corner values to -infinity */`
16. `        arr = Integer.MIN_VALUE;`
17. `        arr[N + 1] = Integer.MIN_VALUE;`
18. ` `
19. `        /* Accept N elements */`
20. `        System.out.println("Enter "+ N +" elements");`
21. `        for (int i = 1; i <= N; i++)`
22. `            arr[i] = scan.nextInt();`
23. ` `
24. `        /* Find All Peak Elements */`
25. `        System.out.println("\nAll Peak Elements : ");`
26. `        for (int i = 1; i <= N; i++)`
27. `            if (arr[i - 1] <= arr[i] && arr[i] >= arr[i + 1])`
28. `                System.out.println(arr[i] +" at position "+ i);`
29. ` `
30. `        System.out.println();    `
31. `    }         `
32. `}`

```Enter size of array
6
Enter 6 elements
1 2 5 5 4 1

All Peak Elements :
5 at position 3
5 at position 4

Enter size of array
7
Enter 7 elements
6 24 15 2 23 99 67

All Peak Elements :
24 at position 2
99 at position 6

Enter size of array
10
Enter 10 elements
10 9 8 24 8 7 97 28 17 63

All Peak Elements :
10 at position 1
24 at position 4
97 at position 7
63 at position 10```

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

If you wish to look at all Java Programming examples, go to Java Programs.

Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs! 