In this program, we are going to share a Java program to find a peak element using divide and conquer rule with the output. If you are a Java beginner and want to start learning the Java programming, then keep your close attention in this tutorial as I am going to share how to write a Java program to find a peak element using divide and conquer rule.
Copy the below Java program and execute it with the help of Javac compiler. At the end of this program, We have shared the output of this program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import java.util.*; import java.lang.*; import java.io.*; class PeakElementProgram { static int findPeakUtil(int arr[], int low, int high, int n) { int mid = low + (high - low)/2; /* (low + high)/2 */ if ((mid == 0 || arr[mid-1] <= arr[mid]) && (mid == n-1 || arr[mid+1] <= arr[mid])) return mid; else if (mid > 0 && arr[mid-1] > arr[mid]) return findPeakUtil(arr, low, (mid -1), n); else return findPeakUtil(arr, (mid + 1), high, n); } static int findPeak(int arr[], int n) { return findPeakUtil(arr, 0, n-1, n); } //main method public static void main (String[] args) { int arr[] = {1, 3, 20, 4, 1, 0}; int n = arr.length; System.out.println("Index of a peak point is " + findPeak(arr, n)); } } |
Index of a peak point is 2
Liked this program? Do Like & share with your friends.
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected]. Your article will appear on the FreeWebMentor main page and help other developers.