How to find Nth largest number in an array

This is the second solution to find the Nth largest number from an array of given numbers. This program uses the Lambda expression, and the internal logic utilizes the sort method of the Arrays class.

import java.util.Arrays;

//Define the functional interface with SAM 'Nth'
interface NthBiggest {
	public int Nth(int[] tmp, int x);
}

public class NthLargest {

	public static void main(String[] args) {

		// Initialized the Array numbers
		int[] numArray = { 34, 21, 45, 75, 62, 98, 13, 49 };
		System.out.println("The given array numbers are here");
		System.out.print("[");

		// Print the Array elements to the console
		dispArray(numArray);

		/* Define the Lambda expression for the functional interface 'NthBiggest' */
		NthBiggest Nb = ((numArr, pos) -> {
			Arrays.sort(numArr);
			return numArr[numArr.length - pos];
		});
		System.out.println("NthLargest number in the Array is=" + Nb.Nth(numArray, 2));
	}

	// The dispArray function with the argument Array
	private static void dispArray(int[] numArray) {
		for (int i = 0; i < numArray.length; i++) {
			System.out.print(numArray[i] + " ");
		}
		System.out.println("]");
	}
}
OUTPUT:
The given array numbers are here
[34 21 45 75 62 98 13 49 ]
The nth largest number in the given Array is=75


Comments

3 responses to “How to find Nth largest number in an array”

  1. I have to get across my passion for your kindness in support of folks that really want help with in this subject matter. Your personal commitment to getting the solution along had been exceptionally useful and has frequently helped most people like me to get to their ambitions. Your own helpful suggestions can mean so much a person like me and still more to my colleagues. Thanks a lot; from each one of us.

    Like

  2. check with this input
    int[] numArray = { -16, -14, -31, -12, -12, -12, -12,-10 }

    Like

    1. Hi Manas,
      Thanks for looking into this blog post.
      You do Try It>> button at the down and replace with your inputs. It’s working
      Thanks

      Like

Leave a comment