×

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 Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.

Salesman Problem in Java

The Traveling Salesman Problem determines the shortest path that visits each city approximately once and loops back to the starting location. Another Java problem that is most like the Traveling...

5 minutes read.

Rectangular Numbers in Java

In this tutorial, we will understand the meaning of a rectangular number in Java with the aid of examples, illustrations, and implementations. It is one of the popular coding interview...

3 minutes read.

Console Errors in Java

An unlawful motion taken through the person that reasons this system to act abnormally is amistake until this system is compiled or run; maximum programming mistakes pass unnoticed.The software is...

3 minutes read.

Java Math log1p() Method

The log1p() method of Math class returns the natural logarithmic sum for the specified double argument and 1. Its value is much closer to result of ln(1 + x). Syntax: public static...

2 minutes read.

Java Thread Dump Analyzer

Thread: A thread is a PC program that is stacked into the PC's memory and is under execution. It tends to be executed by a processor or a bunch of processors....

15 minutes read.

Java While Keyword

Depending on a specified Boolean condition, a while loop in Java allows code to be executed repeatedly. The while loop can be viewed as an iterative version of the if...

3 minutes read.

Self-Descriptive Numbers in Java

A number n is given. Identifying the self-descriptive numbers that exist between 1 and n is our task. Self-Descriptive Numbers The definition of a self-descriptive number, m, is a number with b...

6 minutes read.

Java DatagramSocket and Java DatagramPacket

Datagrams TCP/IP style networking specifies a serialized, predictable, and reliable stream of data in the form of a packet. Servers and clients communicate through a reliable channel, such as TCP socket, have a dedicated...

6 minutes read.

Java Sort String

In this article, you will be acknowledged about how to sort a string in Java. Introduction Firstly, let us revise what is string Strings are collections of characters that are frequently used in...

4 minutes read.

Getting Synchronized Set from Java HashSet

The synchronizedSet() technique for java.util.Collections class is utilized to return a synchronized (string safe) set supported by the predetermined set. To ensure sequential access, it is important that everything admittance...

4 minutes read.

Java Integer hashCode() method

The hashCode()  method of Java Integer class returns a hash code for this Integer.  Syntax public int hashCode() public static int hashCode(int value)  Parameters The parameter ‘value’ represents a value whose hash code...

1 minute read.

Set Value to Enum in Java

In this article, you will be acknowledged about Enum in java. Most importantly you will learn how to set value to Enum or how to practically customize a value to...

3 minutes read.

Best Java Libraries

One of the most widely used programming languages is Java. Java has a large number of libraries, including the standard Java library that includes libraries such as java.lang, java.util, and...

7 minutes read.

How to declare string array in Java

Introduction Array is a data structure with a fixed size, which allows us to store elements of similar type. Data of primitive types like int, char, float, string, etc. can be...

2 minutes read.

Undo and Redo Operations in Java

Undo and redo operation are the most widely used operation while dealing with file. In this section, we will discuss how to implement undo and redo operation in Java. Undo Redo...

2 minutes read.

Java BLOB

The two data types used in Java to store binary and big-character objects are BLOB and CLOB. In contrast to other types of data like float, int, double, etc., it...

4 minutes read.

How to take String Input in Java

There are various ways to take String input in Java. In this section, we are going to discuss how to take String input in Java. There are following ways to...

5 minutes read.

How to increment and decrement date using Java?

Before understanding how to increment and decrement the date, one must know about the Calendar class in Java. The Java calendar class offers methods for converting dates between a given moment...

3 minutes read.