I am trying to find Kth smallest element in an array => val a = Array[Int](10, 1, 7, 2, 25, 11, 14)
To do this, I used the pivot mechanism of quicksort algorithm. Based on the Pivot position, I am recursively calling the pivot method from start to pivot position or from pivot+1 position to the end of the array.
Below is the logic I wrote.
object KthLargestSmallestOfArray extends App {
val a = Array[Int](10, 1, 7, 2, 25, 11, 14)
val k = 3
println(kthSmallest(a, 0, a.length-1, k))
def partition(arr: Array[Int], low: Int, high: Int): Int = {
val pivot = high
var i = low - 1
for(j <- low until high) {
if(arr(j)<arr(pivot)) {
i += 1
swap(arr, i, j)
}
}
swap(arr, i+1, high)
i+1
}
def swap(arr: Array[Int], l: Int, h: Int): Unit = {
val temp = arr(l)
arr(l) = arr(h)
arr(h) = temp
}
@tailrec
def kthSmallest(arr: Array[Int], p: Int, q: Int, index: Int): Int = {
if(p==q && p==index) {
arr(p)
} else {
val r = partition(arr, p, q)
if(r == k) {
arr(r)
} else if(r < k) {
kthSmallest(arr, r+1, q, k)
} else kthSmallest(arr, p, r-1, k)
}
}
}
When I run the code, with input of k = 3, the code is considering 10 as the output.
If I sort the elements of the array => (1, 2, 7, 10, 11, 14, 25), 7 is the third biggest element.
The array has 10 as its 4th element (0 to 3..6) and the array(k) is 10 and hence it is returning 10.
If I supply k as 4, output is 11 and so on.
Is there anyway I can return 7 instead of 10 ? Because 7 is the third smallest element from the beginning which matches with the value of k I am supplying.
Could anyone let me where am I making the mistake and how can I correct it ?
K- Metadataindexinstead ofkin thekthSmallestmethod (or just renameindextok), otherwise you'll use the value outside the local scope instead of the parameter). - stefanobaghino