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.
Given an array of positive and negative unsorted integer. Can you write an algorithm to find out the nth smallest element in the array.
- public class NthSmallestElement {
- public static void main(String[] args) {
- int a[] = { 3, 4, 1, 105, 10, -10 };
- int thirdSmallest = 3;
- int min= nthSmallestElement(a, thirdSmallest );
- System.out.println(min);
- }
- public static int nthSmallestElement(int a[], int n) {
- // Sort the given array
- Arrays.sort(a);
- // Return n'th element in the sorted array
- return a[n - 1];
- }
- }
Output:
3
No comments:
Post a Comment