Selection Sort algorithm

YasserKhalil
PlatinumLounger
Posts: 4911
Joined: 31 Aug 2016, 09:02

Selection Sort algorithm

Post by YasserKhalil »

Hello everyone
In the following code, the numbers are sorted in a descending way.

Code: Select all

Sub Test()
Dim a
a = Array(64, 25, 12, 22, 11, 30, 5)
selectionSort a
Range("A1").Resize(UBound(a) + 1).Value = Application.Transpose(a)
End Sub

 
Function selectionSort(ByVal a)
    Dim tmp, i As Long, j As Long, k As Long
    For i = 0 To UBound(a)
    k = i
        For j = i + 1 To UBound(a)
            If a(j) < a(i) Then
            
    tmp = a(i)
    a(i) = a(j)
    a(j) = tmp
                
            End If
        Next
    Next
    selectionSort = a
End Function
I tried to change the less than to greater than to make the reverse and sort it in ascending way but didn't work

Code: Select all

 If a(j) < a(i) Then

YasserKhalil
PlatinumLounger
Posts: 4911
Joined: 31 Aug 2016, 09:02

Re: Selection Sort algorithm

Post by YasserKhalil »

Sorry I found the solution after putting the question

Code: Select all

a = selectionSort(a)