×

VB.Net Programs

VB.Net program to implement quicksort using recursion

By Nidhi Last Updated : November 15, 2024

Quicksort using recursion

Here, we will create an array of integers and then read elements from the user. After we sort the array element using quicksort and then print the sorted array on the console screen.

Program/Source Code:

The source code to implement quicksort using recursion is given below. The given program is compiled and executed successfully.

VB.Net code to implement quicksort using recursion

'VB.Net program to implement quicksort using recursion.

Module Module1
    Private Sub QuickSort(ByVal arr() As Integer, ByVal first As Integer, ByVal last As Integer)
        Dim pivot As Integer = 0
        Dim temp As Integer = 0
        Dim i As Integer = 0
        Dim j As Integer = 0

        If first < last Then
            pivot = first
            i = first
            j = last

            While (i < j)
                While (arr(i) <= arr(pivot) AndAlso i < last)
                    i = i + 1
                End While

                While (arr(j) > arr(pivot))
                    j = j - 1
                End While

                If i < j Then
                    temp = arr(i)
                    arr(i) = arr(j)
                    arr(j) = temp
                End If
            End While

            temp = arr(pivot)
            arr(pivot) = arr(j)
            arr(j) = temp
            QuickSort(arr, first, j - 1)
            QuickSort(arr, j + 1, last)
        End If
    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

        QuickSort(arr, 0, 4)

        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]: 43
Element[1]: 65
Element[2]: 34
Element[3]: 25
Element[4]: 87
Array element after sorting:
25 34 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 a function QuickSort() to the elements of the array. Using the QuickSort method, we divide the input array into small sub-arrays. Then we sort sub-arrays recursively.

VB.Net Array Programs »


Comments and Discussions!

Load comments ↻





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