Saturday, August 24, 2019

Write an algorithm to find N’th smallest 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 smallest element in the array.

  1. public class NthSmallestElement {
  2. public static void main(String[] args) {
  3. int a[] = { 3, 4, 1, 105, 10, -10 };
  4.   int thirdSmallest = 3;
  5. int min= nthSmallestElement(a, thirdSmallest );
  6. System.out.println(min);
  7. }
  8. public static int nthSmallestElement(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[n - 1];
  13. }
  14. }
Output:
3

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...