JavaScript Program to find the Nth smallest/largest element from an unsorted Array
Last Updated :
24 May, 2024
In this article, we will see how to find Nth largest and smallest element from an unsorted array. The Nth smallest/largest element from an unsorted array refers to the element that ranks at the Nth position when the array is sorted either in ascending (smallest) or descending (largest) order. It represents the value at the Nth position when considering all unique values in the array.
Examples:
Input:
arr[]={1, 3, 2, 4, 8, 7, 5, 6},
N=3
Output:
largest=6,
smallest=3
There are several methods that can be used to find the Nth smallest/largest element from an unsorted Array in JavaScript, which are listed below:
We will explore all the above methods along with their basic implementation with the help of examples.
In this approach, we sort the given array in descending or ascending order and return the element at the N-1 index.
Follow the given steps to solve the problem (Nth Smallest):
- Sort the input array in ascending order.
- Return the element at the N-1 index in the sorted array(0 – Based indexing).
Follow the given steps to solve the problem (Nth Largest):
- Sort the input array in the descending order.
- Return the element at the N-1 index in the sorted array (0 – Based indexing).
Syntax:
array.sort();
Example: Below is the implementation of the above approach.
JavaScript
let arr = [1, 3, 2, 4, 8, 7, 5, 6];
let n = 3;
let largest = (arr, n) => {
arr.sort((a, b) =>
b - a); return arr[n - 1]
};
let smallest = (arr, n) => {
arr.sort((a, b) =>
a - b); return arr[n - 1]
};
console.log("N'th Largest ", largest(arr, n));
console.log("N'th Smallest ", smallest(arr, n));
OutputN'th Largest 6
N'th Smallest 3
Using Set() Method
Set data structure is used to find the Nth smallest as well as largest element, it stores the distinct elements in the sorted order.
Follow the given steps to solve the problem:
- Insert all the elements of an array into the set.
- we are using Sets (NthSmallestSet and NthLargestSet) to remove duplicate values from the array.
- Sort the set accordingly in ascending or descending order.
- Move index iterator to reach Nth element in the set
- Return the value of the element at which the index iterator is pointing.
Note: Set can only be used when elements are distinct.
Syntax:
new Set([it]);
Example: Below is the implementation of the above approach.
JavaScript
let arr = [1, 3, 2, 4, 8, 7, 5, 6];
let Nth_smallest = 3;
let NthSmallest = new Set([...arr]);
NthSmallest = [...NthSmallest].sort((a, b) => a - b);
let NthLargest = new Set([...arr]);
NthLargest = [...NthLargest].sort((a, b) => b - a);
for (const index of NthSmallest.values()) {
if (Nth_smallest === 1) {
console.log("N'th Smallest : ", index);
break;
}
Nth_smallest = Nth_smallest - 1;
}
let Nth_largest = 3;
for (const index of NthLargest.values()) {
if (Nth_largest === 1) {
console.log("N'th Largest : ", index);
break;
}
Nth_largest = Nth_largest - 1;
}
OutputN'th Smallest : 3
N'th Largest : 6
Using Quickselect Algorithm
Quickselect is a selection algorithm similar to Quicksort. It selects the kth smallest/largest element from an unsorted array in expected O(n) time complexity, where n is the number of elements in the array.
Follow the given steps to solve the problem:
- Choose a pivot element from the array.
- Partition the array into two sub-arrays: elements less than the pivot and elements greater than the pivot.
- Recur for the appropriate sub-array based on the position of the pivot after partitioning.
- Repeat the process until the pivot element is the kth smallest/largest element.
Syntax:
function quickSelect(arr, left, right, k) { }
Example: Below is the implementation of the above approach.
JavaScript
function partition(arr, left, right) {
let pivot = arr[right];
let i = left - 1;
for (let j = left; j < right; j++) {
if (arr[j] < pivot) {
i++;
[arr[i], arr[j]] = [arr[j], arr[i]];
}
}
[arr[i + 1], arr[right]] = [arr[right], arr[i + 1]];
return i + 1;
}
function quickSelect(arr, left, right, k) {
if (left === right) return arr[left];
let pivotIndex = partition(arr, left, right);
if (k - 1 === pivotIndex) {
return arr[pivotIndex];
} else if (k - 1 < pivotIndex) {
return quickSelect(arr, left, pivotIndex - 1, k);
} else {
return quickSelect(arr, pivotIndex + 1, right, k);
}
}
let arr = [1, 3, 2, 4, 8, 7, 5, 6];
let k = 3;
console.log("N'th Smallest: ", quickSelect(arr.slice(), 0, arr.length - 1, k));
console.log("N'th Largest: ", quickSelect(arr.slice(), 0, arr.length - 1, arr.length - k + 1));
OutputN'th Smallest: 3
N'th Largest: 6
Similar Reads
JavaScript Program to Find kth Largest/Smallest Element in an Array JavaScript allows us to find kth largest/smallest element in an array. We are given an array containing some elements, we have to find kth smallest/largest element from the array where k is a number greater than zero and less than equal to the total number of elements present in the array. There are
5 min read
JavaScript Program to Find Kth Smallest/Largest Element in a Sorted Matrix Given an n x n matrix, where every row and column is sorted in non-decreasing order. Find the kth smallest/largest element in the given 2D array. Examples: Input:k = 3 and array = 10, 20, 30, 40 15, 25, 35, 45 24, 29, 37, 48 32, 33, 39, 50 Output: 20 40Explanation: The 3rd smallest element is 20 The
3 min read
JavaScript Program to Find Largest Element in an Array In this article, we are going to learn about the largest element in an array in JavaScript. The largest element in an array refers to the value that holds the greatest numerical or lexicographic (string) order among all elements present in the array. Example: Input : [10, 15, 38, 20, 13];Output: 38H
3 min read
Javascript Program for Third largest element in an array of distinct elements Given an array of n integers, find the third largest element. All the elements in the array are distinct integers. Example : Input: arr[] = {1, 14, 2, 16, 10, 20}Output: The third Largest element is 14Explanation: Largest element is 20, second largest element is 16 and third largest element is 14Inp
6 min read
Javascript Program for Find the smallest missing number Given a sorted array of n distinct integers where each integer is in the range from 0 to m-1 and m > n. Find the smallest number that is missing from the array. Examples:Input: {0, 1, 2, 6, 9}, n = 5, m = 10 Output: 3 Input: {4, 5, 10, 11}, n = 4, m = 12 Output: 0 Input: {0, 1, 2, 3}, n = 4, m =
4 min read
Javascript Program To Find Next Greater Element Given an array, print the Next Greater Element (NGE) for every element. The Next greater Element for an element x is the first greater element on the right side of x in the array. Elements for which no greater element exist, consider the next greater element as -1. Examples: For an array, the righ
6 min read
Javascript Program For Rearranging An Array In Maximum Minimum Form - Set 2 (O(1) extra space) Given a sorted array of positive integers, rearrange the array alternately i.e first element should be the maximum value, second minimum value, third-second max, fourth-second min and so on. Examples:Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: arr[] = {7, 1, 6, 2, 5, 3, 4}Input: arr[] = {1, 2, 3, 4
5 min read
Javascript Program For Sorting An Array Of 0s, 1s and 2s Given an array A[] consisting 0s, 1s and 2s. The task is to write a function that sorts the given array. The functions should put all 0s first, then all 1s and all 2s in last.Examples:Input: {0, 1, 2, 0, 1, 2}Output: {0, 0, 1, 1, 2, 2}Input: {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}Output: {0, 0, 0, 0, 0
5 min read
JavaScript Program to Find Top k Elements Given an array, our task is to find the top k elements in an unsorted array of integers in JavaScript, either the largest or the smallest. Duplicate values may be in the array. The output will be a new array with the top k elements arranged in a non-ascending order (from largest to smallest). Table
4 min read
JavaScript Program for Insertion Sort What is Insertion Sort Algorithm?Insertion sorting is one of the sorting techniques that is based on iterating the array and finding the right position for every element. It compares the current element to the predecessors, if the element is small compare it with the elements before. Move ahead to a
4 min read