Home »
VB.Net »
VB.Net Programs
VB.Net program to sort an integer array using Radix sort
By Nidhi Last Updated : November 16, 2024
Sort an integer array using Radix sort
Here, we will create an array of integers and then read elements from the user. After we sort the array element using radix sort and then print sorted array on the console screen.
Program/Source Code:
The source code to sort an integer array using Radix sort is given below. The given program is compiled and executed successfully.
VB.Net code to sort an integer array using Radix sort
'VB.Net program to sort an integer array using Radix sort.
Module Module1
Function GetMax(ByVal arr() As Integer, ByVal n As Integer) As Integer
Dim max As Integer = arr(0)
For i = 1 To n - 1 Step 1
If (arr(i) > max) Then
max = arr(i)
End If
Next
GetMax = max
End Function
Sub countSort(ByVal arr() As Integer, ByVal n As Integer, ByVal exp As Integer)
Dim output As Integer() = New Integer(n) {}
Dim count As Integer() = New Integer(10) {}
Dim t As Integer = 0
For i = 0 To n - 1 Step 1
t = (arr(i) \ exp) Mod 10
count(t) = count(t) + 1
Next
For i = 1 To 9 Step 1
count(i) = count(i) + count(i - 1)
Next
For i = (n - 1) To 0 Step -1
output(count((arr(i) / exp) Mod 10) - 1) = arr(i)
t = (arr(i) \ exp) Mod 10
count(t) = count(t) - 1
Next
For i = 0 To n - 1 Step 1
arr(i) = output(i)
Next
End Sub
Sub RadixSort(ByVal arr() As Integer, ByVal n As Integer)
Dim m As Integer = GetMax(arr, n)
Dim exp As Integer = 1
Dim val As Integer = 0
val = m \ exp
While (val > 0)
countSort(arr, n, exp)
exp = exp * 10
val = m \ exp
End While
End Sub
Sub Main()
Dim arr As Integer() = New Integer(5) {}
Console.WriteLine("Enter array elements: ")
For i = 0 To 4 Step 1
Console.Write("Element[{0}]: ", i)
arr(i) = Integer.Parse(Console.ReadLine())
Next
RadixSort(arr, 5)
Console.WriteLine("Array element after sorting: ")
For i = 0 To 4 Step 1
Console.Write("{0} ", arr(i))
Next
Console.WriteLine()
End Sub
End Module
Output
Enter array elements:
Element[0]: 32
Element[1]: 43
Element[2]: 12
Element[3]: 65
Element[4]: 87
Array element after sorting:
12 32 43 65 87
Press any key to continue . . .
Explanation
In the above program, we created a module Module1 that contains a function Main(). In the Main() we created an array arr of five elements and we created three functions GetMax(), CountSort(), and RadixSort() to sort array elements using Radix Sort technique.
VB.Net Array Programs »