Last active
December 24, 2019 18:05
-
-
Save pbesra/6a44cfb6f3909da5e613fa4054c17c1b to your computer and use it in GitHub Desktop.
Peak finding algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Algorithm | |
// Input: Array A[n], find a peak element in araray A. The peak element is | |
//not necessarily a global maxima | |
/* | |
For an element,Search(A, 0, A.length-1) | |
midElement=(start+end)/2 | |
1. If (midElement==end && a[midElement]>=a[midElement-1]) || (midElement==0 && a[midElement]>=a[midElement+1]) || (A[midElement]>=A[midElement-1] && A[midElement]>=A[midElement+1]) | |
----> return mid | |
2. else if(A[midElement-1]>A[midElement]) | |
-----> Search left array Search(A, sstart, midElement-1) | |
3. else | |
-----> Search right array Search(A, midElement+1, end) | |
*/ | |
public class Test { | |
static int PeakElement(int[] a, int s, int n){ | |
if(s<=n){ | |
int mid=(s+n)/2; | |
if(a[mid-1]>a[mid]){ | |
//System.out.println("if: "+a[mid]); | |
return PeakElement(a, s, mid-1); | |
}else if(a[mid]<a[mid+1]){ | |
//System.out.println("else: "+a[mid]); | |
return PeakElement(a, mid+1, n); | |
}else{ | |
return mid; | |
} | |
} | |
return -1; | |
} | |
public static void main(String[] args) { | |
int[] a={40, 10, 120, 5, 145, 50, 65, 90, 100, 20}; | |
int[] b={1, 2, 3, 4, 5}; | |
int x=PeakElement(a, 0, a.length-1); | |
System.out.println(a[x]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment