Finding Kth smallest or largest element of an array has many intuitive solutions. But in this article, we will only cover the simple array-based approach as this series is dedicated to solving the array section of DSA450. We will probably revisit this or a similar problem in the sorting and searching section.
The easiest approach to finding the kth
maximum or minimum element would be to sort the array and return the element at k-1 th
index(for minimum) and n-k th
index(for maximum).
Here is a quick code snippet for this approach.
function k_min_max_ele(arr, k) {
arr.sort();
// [-1, 0, 1, 2, 3, 4, 5, 7]
return {
minimum: arr[k - 1],
maximum: arr[arr.length - k],
};
}
console.log(k_min_max_ele([1, 3, 2, 4, 5, -1, 0, 7], 3));
-> { minimum: 1, maximum: 4 }
As we can see, 1 is the 3rd smallest element and 4 is the 3rd largest element of this array.
That is it for this post! Next, we will sort an array of 0s, 1s and 2s.