To find the kth minimum and maximum element in an array, you can first sort the array and then return the kth element. Here’s an example implementation in Kotlin:
fun findKthMinMax(arr: IntArray, k: Int): Pair<Int, Int>? {
val n = arr.size
if (n == 0 || k <= 0 || k > n) {
return null
}
val sortedArr = arr.sortedArray()
return Pair(sortedArr[k-1], sortedArr[n-k])
}
fun main(){
val arr = intArrayOf(1, 2, 3, 4, 5)
val k = 2
val kthMinMax = findKthMinMax(arr, k)
if (kthMinMax != null) {
val (kthMin, kthMax) = kthMinMax
println("$k-th minimum element: $kthMin")
println("$k-th maximum element: $kthMax")
} else {
println("Array is empty or invalid k value")
}
}
findKthMinMax
takes an IntArray
as input along with an integer k
indicating which kth minimum and maximum elements to find, and returns a nullable Pair<Int, Int>
containing the kth minimum and maximum elements. The function first gets the length of the array n
. If the length is 0 or if k is less than or equal to 0 or greater than the length of the array, the function returns null
. Otherwise, it sorts the array using the sortedArray()
function and returns a Pair
containing the kth element (at index k-1
since arrays are zero-indexed) and the (n-k)th element from the end of the array.
This code creates an integer array arr
, specifies the value of k as 2, calls the findKthMinMax
function to find the kth minimum and maximum elements, and prints the result. The output of this code will be:
2-th minimum element: 2
2-th maximum element: 4
Note that this implementation sorts the entire array, which has a time complexity of O(n log n). If you’re interested in finding the kth element using a more efficient algorithm with a time complexity of O(n), you can look into algorithms such as quickselect or heapselect.