×

VB.Net Programs

VB.Net program to sort an array in descending order using bubble sort

By Nidhi Last Updated : November 16, 2024

Sort an array in descending order using bubble sort

Here, we will sort an array of integers in the descending order using bubble sort, and then print sorted array on the console screen.

Program/Source Code:

The source code to sort an array in descending order using bubble sort is given below. The given program is compiled and executed successfully.

VB.Net code to sort an array in descending order using bubble sort

'VB.Net program to sort an integer array in the 
'descending order using bubble sort.

Module Module1

    Sub Main()
        Dim arr As Integer() = New Integer(5) {}
        Dim temp As Integer = 0
        Dim i, j 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 bubble sort.
        For i = 0 To 4 Step 1
            For j = 4 To i + 1 Step -1
                If (arr(j) > arr(j - 1)) Then
                    temp = arr(j)
                    arr(j) = arr(j - 1)
                    arr(j - 1) = temp
                End If
            Next
        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]: 23
Element[1]: 54
Element[2]: 32
Element[3]: 15
Element[4]: 64
Array after sorting:
64 54 32 23 15
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 a variable temp which is 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 descending order using bubble sort.
For i = 0 To 4 Step 1
    For j = 4 To i + 1 Step -1
        If (arr(j) > arr(j - 1)) Then
            temp = arr(j)
            arr(j) = arr(j - 1)
            arr(j - 1) = temp
        End If
    Next
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 descending order using bubble sort, in the each phase of bubble sort smallest element get moved to the last. After sorting process, we printed the sorted array on the console screen.

VB.Net Array Programs »


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.