×

Local Minima in Java

An Array

Finding a local minimum in an array a[0. m-1] of different integers is the job. A[i] is considered a local minimum if it is smaller than two of its neighbors.

When comparing corner elements, we only need to take into account one neighbor.

There may be more than one local minimum in an array; we must select one of them.

Examples:

Input: a[] = {18, 15, 13, 3, 14, 14, 15};

result: Index of local minima is 2

Since the result is smaller than both of its neighbors, the index of 13 is printed. Remember that the elements 15 and 14's indexes are likewise acceptable outputs.

Input: a[] = {2, 7, 1, 7, 2};

result: Index of local minima is 2

Input: a[] = {7, 8, 9};

result: Index of local minima is 0

Input: a[] = {9, 8, 7};

result: Index of local minima is 8

Doing a linear scan of the array and returning it as soon as a local minima is discovered is a straightforward approach. The method's worst-case temporal complexity is O. (n).

Binary Search is the foundation of an effective solution. We evaluate the Centre element's neighbors. We return the middle element if it is not bigger than any of its neighbors. There will always be a local minima in the left half if the middle element is larger than its left neighbor (to see why, consider a few examples).There will always be a local minimum in the right half if the central element is larger than its right neighbour (due to same reason as left half).

// A C++ prog to demonstrate a local minima in an array


#include <stdio.h>


// a function that uses binary search and returns the index of a local minima.


int localMinUtil(int a[], int l, int h, int m)


{


    // Find the middle element's index.


    int mid = l + (h - l)/2;  /* (l + h)/2 */


    // Compared to its neighbours, the middle element (if neighbours exist)


    if ((mid == 0 || a[mid-1] > a[mid]) &&


            (mid == m-1 || a[mid+1] > a[mid]))


        return mid;


    // Left half must include a local minimum if the centre element is not a minima and its left neighbour is smaller than it.


    else if (mid > 0 && a[mid-1] < a[mid])


        return localMinUtil(a, l, (mid -1), m);


    //Right half must include a local minimum if centre element is not a minima and its right neighbour is smaller than it.


    return localMinUtil(a, (mid + 1), h, m);


}


// recursive function localMinUtil wrapper ()


int localMin(int a[], int m)


{


    return localMinUtil(a, 0, m-1, m);


}


/* Driver application to verify the aforementioned features*/


int main()


{


    int a[] = {41, 31, 1, 13, 18, 4};


    int m = sizeof(a)/sizeof(a[0]);


printf("Index of a local minima is %d",


                           localMin(a, m));


    return 0;


}

Output:

Index of a local minima is 2

Java program

// A Java prog to demonstrate a local minima in an array


import java.io.*;


class LM


{


    // a function that uses binary search and returns the index of a local minima.


    public static int localMinUtil(int[] a, int l,int h, int m)


    {


        // Find index of middle element


        int mid = l + (h - l) / 2;


         // Compared to its neighbours, the middle element (if neighbours exist)


        if(mid == 0 || a[mid - 1] > a[mid] && mid == m - 1 ||


           a[mid] < a[mid + 1])


                return mid;


        // Left half must include a local minimum if the centre element is not a minima and its left neighbour is smaller than it.


        else if(mid > 0 && a[mid - 1] < a[mid])


                return localMinUtil(a, l, mid - 1, m);


        // Right half must include a local minimum if centre element is not a minima and its right neighbour is smaller than it.


        return localMinUtil(a, mid + 1, h, m);


    }


    //recursive function localMinUtil wrapper ()


    public static int localMin(int[] a, int m)


    {


        return localMinUtil(a, 0, m - 1, m);


    }


    public static void main (String[] args)


    {


        int a[] = {44, 33, 10, 13, 10, 48};


        int m = a.length;


System.out.println("Index of a local minima is " + localMin(a, m));


    }


}

Output:

Index of local minima is 1

Time Complexity: O(Log n)

Auxiliary Space: O (log n), The implicit stack is used since the recursive call is present.


Related Topics

Java Localization

Internationalization is the process of creating a software application that can be translated into different languages and regions without modifying the application. Creating a locale-specific application raises the cost of...

3 minutes read.

Java Char Keyword

The java char keyword is a data type which is defined as character data type.Char keyword belongs to a primitive data type where the data types are classified into primitive...

4 minutes read.

if-else Program in Java

if-else Program in Java The if-else program in Java controls which code snippet will execute. The if-else program is very basic and yet very important. Because it checks how well one...

19 minutes read.

Uses of Java

Java is used in many real-world Java applications, including technologies and tools. This Java programming language has become the backbone for developing many applications. In areas like embedded systems and...

3 minutes read.

Bottom view of a binary tree in Java

The lowest nodes in their horizontal distance are present and referred to as the bottom view of a binary tree. The horizontal distance between the nodes of a binary tree...

4 minutes read.

Java Boolean toString() Method

The toString() method of Java Boolean class returns a String corresponding to this Boolean object. It returns a string value “true”, if the defined object is true else it returns...

2 minutes read.

Java 8 Features

Java 8 Features: After the great success of Java 7, many developers were waiting for the next version of one of the best languages in the tech world. Moreover, on...

6 minutes read.

Permutation Coefficient in Java

In this tutorial, we will get familiar with the permutation coefficient in Java.  We will understand it through examples and see different approaches to solving the problem. A permutation is a...

5 minutes read.

Java Integer compareTo() method

The compareTo() method of Integer class compares two Integer objects numerically. Syntax public static int compareTo(int anotherInteger) Parameters The parameter ‘anotherInteger’ represents the Integer to be compared. Specified by This method is specified by compareTo in...

2 minutes read.

Java String length() method

Java String length() method returns length of the characters in a String. Syntax: public int length() Returns It returns length of the characters Java String length() method example 1          public class JavaStringLengthEx1  ...

1 minute read.

Iccanobif Numbers in Java

In this article, you will be very well equipped with the knowledge of iccanobif numbers in Java. You will also know how they are formed and basic example programs on...

3 minutes read.

Java time local date

Java: Java is one of the programming language which is object oriented. It consists of many features such as robust, simple, architecture neutral, dynamic, distributed, multi threaded, portable etc. The main feature...

3 minutes read.

Access Modifier in Java

The access modifiers in java are used to change the accessibility and scope of a method, constructor, class, and fields. If you are aware of C++ language, when we declare any member...

2 minutes read.

Minimum Lights to Activate Java Snippet Class

Minimum Lights to Activate Problem in Java In prison, there is a hallway that is N units long. Given an N-dimensional array A. If the light at the ith position is...

3 minutes read.

Convert List to String in Java

We occasionally need to create a string from a list of characters. Since a string is only a collection of characters, a character array can be converted into a string....

6 minutes read.

Java finally

Java finally: There are some statements in a program whose execution is extremely important. For example, closing of a database connection. Statements that do the closing of the database connection...

5 minutes read.

Concurrent Modification Exception In Java

When an object is attempted to be updated concurrently when it is not allowed, the ConcurrentModificationException arises. This error typically occurs while using Java Collection classes. When another thread is iterating...

5 minutes read.

Java String Reader

StreamReaderClass: This class is present in the java.io package. It is a character stream in which string act as a source.This method provides to read characters from a string. Character Stream: This class...

3 minutes read.

Types of Assignment Operators in Java

In this tutorial, we are going to study assignment operators and their types in Java language. Before proceeding to the types, let us know the term ‘assignment operator’.  The assignment...

5 minutes read.

Arithmetic Operations on String in Java

Introduction Arithmetic, Relational, Bitwise, and Logical operators are all available in Java. Simple mathematical calculations are performed using Java arithmetic operators. Basic Arithmetic operators are considered in Java to be Addition,...

4 minutes read.