Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,938 questions

51,875 answers

573 users

How to find the peak element (element that is greater than its neighbors) on an array in C

2 Answers

0 votes
#include <stdio.h> 

int find_peak_element(int arr[], int low, int high, int len) {
	int mid = (low + high) / 2;

	if ((mid == 0 || arr[mid - 1] <= arr[mid]) && (mid == len - 1 || arr[mid + 1] <= arr[mid])) {
		return mid;
	}

	if (mid - 1 >= 0 && arr[mid - 1] > arr[mid]) {
		return find_peak_element(arr, low, mid - 1, len);
	}

	return find_peak_element(arr, mid + 1, high, len);
}

int main(void) 
{ 
	int arr[] = { 5, 6, 9, 5, 1, 4, 1 };
	int len = sizeof(arr) / sizeof(arr[0]);

	int i = find_peak_element(arr, 0, len - 1, len);
	
	printf("%i\n", arr[i]);
     
    return 0; 
} 
  
  
  
/*
run:
  
9
 
*/

 



answered Aug 6, 2019 by avibootz
0 votes
#include <stdio.h> 

int find_peak_element(int arr[], int start, int end, int len) {
	if (len == 0) {
		return -1;
	}
	while (start <= end) {
		int mid = (int)((start + end) / 2);
		if ((mid == 0 || arr[mid - 1] <= arr[mid]) && (mid == len - 1 || arr[mid] >= arr[mid + 1])) {
			 return mid;  
		} else if (mid > 0 && arr[mid - 1] > arr[mid]) {
					end = mid - 1;
	           } else {
						start = mid + 1;
				 }
	}
	return -1;
}

int main(void) 
{ 
	int arr[] = { 5, 6, 9, 5, 5, 4, 1 };
	int len = sizeof(arr) / sizeof(arr[0]);

	int i = find_peak_element(arr, 0, len - 1, len);
	
	(i == -1) ? printf("Not Found") : printf("%i\n", arr[i]);
     
    return 0; 
} 
  
  
  
/*
run:
  
9
 
*/

 



answered Aug 7, 2019 by avibootz
...