Seven Bubble sort for you: which do you choose?
#21
Hi
here a recursive vs iterative methods demonstration about bubblesort the original algorithm:
Code: (Select All)
$Debug
Const max = 5 '32767
Randomize Timer

Type DATATYPE
    a As Integer
    b As Integer
    c As Integer
End Type

ReDim SortedList(1 To max) As DATATYPE, t(1 To max) As DATATYPE

'The sort will only be done on the value of 'a' (SortedList().a) and the values can range from 1 to 32767.
init SortedList() ' this is the original array created at random
initT SortedList(), t() ' this copies the first array into the second array

Print "original array "
ShowArray t()
_Delay 2
BubbleRecursive t(), 0, 0
Color 3
Print " Bubble Recursive order"
ShowArray t()
Color 7
Print "press a key to continue...";
Sleep

initT SortedList(), t()
Print "Original array"
ShowArray t()
_Delay 2
Print "ordering..."
bubble t()
Color 2
Print "Bubble Iterative order"
ShowArray t()
Color 7
_Delay 2
End


Sub BubbleRecursive (a() As DATATYPE, Noswap As Integer, c As Integer)
    If Noswap = 0 Then
        Noswap = -1
        If c < (max - 1) Then
            c = c + 1
            If a(c).a > a(c + 1).a Then
                Swap a(c).a, a(c + 1).a
                Noswap = 0
            End If
        Else
            ' c => max-1
            If Noswap = 0 Then c = 1
        End If
        BubbleRecursive a(), Noswap, c
    End If
End Sub

Sub bubble (a() As DATATYPE)
    ' bubblesort
    ' we compare 2 sequential elements of a set of elements until no swap has been performed
    ' while the first element is higher/lower (increasing/decreasing order) than the second element we swap the 2 elements
    NoSwap = 0
    While NoSwap = 0
        NoSwap = -1
        For count = 1 To max - 1
            If a(count).a > a(count + 1).a Then Swap a(count), a(count + 1): NoSwap = 0
        Next count
    Wend
End Sub


Sub initT (b() As DATATYPE, a() As DATATYPE)
    For count = 1 To max
        a(count).a = b(count).a
    Next count
End Sub

Sub init (a() As DATATYPE)
    For count = 1 To max
        a(count).a = (Rnd * max - 1) + 1
    Next count
End Sub

Sub ShowArray (A() As DATATYPE)
    For count = 1 To max
        Print A(count).a
    Next count
End Sub
Reply


Messages In This Thread
RE: Seven Bubble sort for you: which do you choose? - by TempodiBasic - 03-19-2023, 11:22 PM



Users browsing this thread: 2 Guest(s)