Home »
VB.Net »
VB.Net Programs
VB.Net program to sort an array in ascending order using insertion sort
By Nidhi Last Updated : November 16, 2024
Sort an array in ascending order using insertion sort
Here, we will sort an array of integers in the ascending order using insertion sort, and then print sorted array on the console screen.
Program/Source Code:
The source code to sort an array in ascending order using insertion sort is given below. The given program is compiled and executed successfully.
VB.Net code to sort an array in ascending order using insertion sort
'VB.Net program to sort an integer array in the
'ascending order using insertion sort.
Module Module1
Sub Main()
Dim arr As Integer() = New Integer(5) {}
Dim item As Integer = 0
Dim flag As Integer = 0
Dim loop1 As Integer = 0
Dim loop2 As Integer = 0
Dim i As Integer = 0
Console.WriteLine("Enter array elements: ")
For i = 0 To 4 Step 1
Console.Write("Element[{0}]: ", i)
arr(i) = Integer.Parse(Console.ReadLine())
Next
'Sort array in descending order using insertion sort.
For loop1 = 1 To 4 Step 1
item = arr(loop1)
flag = 0
loop2 = loop1 - 1
While (loop2 >= 0 And flag <> 1)
If (item < arr(loop2)) Then
arr(loop2 + 1) = arr(loop2)
loop2 = loop2 - 1
arr(loop2 + 1) = item
Else
flag = 1
End If
End While
Next
Console.WriteLine("Array 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]: 43
Element[1]: 57
Element[2]: 32
Element[3]: 16
Element[4]: 28
Array after sorting:
16 28 32 43 57
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 four variables item, flag , loop1, and loop2 that are initialized with 0.
Console.WriteLine("Enter array elements: ")
For i = 0 To 4 Step 1
Console.Write("Element[{0}]: ", i)
arr(i) = Integer.Parse(Console.ReadLine())
Next
In the above code, we read the elements of the array from the user.
'Sort array in ascending order using insertion sort.
For loop1 = 1 To 4 Step 1
item = arr(loop1)
flag = 0
loop2 = loop1 - 1
While (loop2 >= 0 And flag <> 1)
If (item < arr(loop2)) Then
arr(loop2 + 1) = arr(loop2)
loop2 = loop2 - 1
arr(loop2 + 1) = item
Else
flag = 1
End If
End While
Next
Console.WriteLine("Array after sorting: ")
For i = 0 To 4 Step 1
Console.Write("{0} ", arr(i))
Next
Console.WriteLine()
Using above given code, we sort the array in the ascending order using insertion sort and print the sorted array on the console screen.
VB.Net Array Programs »