Find a local minima in an array in C++


Suppose we have an array A with n elements. We have to find the local minima of the array. In array A, the element A[x] is said to be local minima if it is less than or equal to both of its neighbors. For corner elements only one neighbor will be considered. And if there are more than one local minima available, then return only one. For example, if the array is like [9, 6, 3, 14, 5, 7, 4], then the local minima can be 3, 5 and 4, so this algorithm can return only one of them.

To solve this problem, we will follow the logic like binary search. If the middle element is lesser than its left and right elements, then return mid, otherwise, if it is greater than left neighbor, then there may be some local minima at left hand side, if it is greater than the right element, then there will be some local minima at right, do the same task for them to find exact local minima.

Example

 Live Demo

#include<iostream>
using namespace std;
int localMinima(int arr[], int left, int right, int n) {
   int mid = left + (right - left)/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 localMinima(arr, left, (mid -1), n);
   return localMinima(arr, (mid + 1), right, n);
}
int findLocalMinima(int arr[], int n) {
   return localMinima(arr, 0, n-1, n);
}
int main() {
   int arr[] = {9, 6, 3, 14, 5, 7, 4};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout << "Local minima is: " << arr[findLocalMinima(arr, n)];
}

Output

Local minima is: 3

Updated on: 18-Dec-2019

280 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements