Imports System
Module Program
' Entry point of the program
Sub Main()
' Example data
Dim numbers() As Integer = {42, 90, 50, 30, 37, 21, 83, 45}
Dim k As Integer = 3
' Find the Kth smallest value using a dedicated function
Dim result As Integer = FindKthSmallest(numbers, k)
Console.WriteLine($"The {k}rd smallest number is: {result}")
End Sub
' Finds the Kth smallest element using the Quickselect algorithm.
' This approach avoids fully sorting the array, improving efficiency.
Function FindKthSmallest(values() As Integer, k As Integer) As Integer
' Quickselect works in-place, so we operate on a copy to avoid mutating the original array.
Dim data() As Integer = CType(values.Clone(), Integer())
' Convert K to zero-based index
Dim targetIndex As Integer = k - 1
Return QuickSelect(data, 0, data.Length - 1, targetIndex)
End Function
' Quickselect recursively partitions the array until the pivot lands on the desired index.
Function QuickSelect(arr() As Integer, left As Integer, right As Integer, targetIndex As Integer) As Integer
While True
' Partition the array and get the pivot's final position
Dim pivotIndex As Integer = Partition(arr, left, right)
If pivotIndex = targetIndex Then
' Found the exact position of the Kth smallest element
Return arr(pivotIndex)
ElseIf targetIndex < pivotIndex Then
' Search the left partition
right = pivotIndex - 1
Else
' Search the right partition
left = pivotIndex + 1
End If
End While
return -1
End Function
' Rearranges elements so that:
' - Items less than the pivot are moved to the left
' - Items greater than the pivot are moved to the right
' Returns the pivot's final index.
Function Partition(arr() As Integer, left As Integer, right As Integer) As Integer
Dim pivotValue As Integer = arr(right)
Dim storeIndex As Integer = left
For i As Integer = left To right - 1
If arr(i) < pivotValue Then
Swap(arr, i, storeIndex)
storeIndex += 1
End If
Next
' Move pivot to its final position
Swap(arr, storeIndex, right)
Return storeIndex
End Function
' Swaps two elements in the array
Sub Swap(arr() As Integer, i As Integer, j As Integer)
Dim temp As Integer = arr(i)
arr(i) = arr(j)
arr(j) = temp
End Sub
End Module
' run:
'
' The 3rd smallest number is: 37
'