Saturday, August 24, 2019

Write an algorithm to find N’th largest element in an Unsorted Array.

Problem statement:
Given an array of positive and negative unsorted integer. Can you write an algorithm to find out the nth largest element in the array.
  1. public class NthLargestElement {
  2. public static void main(String[] args) {
  3. int a[] = { 3, 4, 1, 105, 10, -10 };
  4.                 int thirdLargest = 3;
  5. int max = nthLargestElement(a, thirdLargest);
  6. System.out.println(max);
  7. }
  8. public static int nthLargestElement(int a[], int n) {
  9. // Sort the given array
  10. Arrays.sort(a);
  11. // Return n'th element in the sorted array
  12. return a[a.length - n];
  13. }
  14. }
Output:
4

No comments:

Post a Comment

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...