Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
GnomeSort
#1
Rosetta code didn't have a QB64 version of a Gnome Sort so I made one.
Code: (Select All)
'GnomeSort.bas
'a sorting algorithm that will sort a one dimensional array of any size from lowest to greatest value
'https://en.wikipedia.org/wiki/Gnome_sort
'initialize two different one dimensional arrays to demonstrate the subroutine
Randomize Timer
Dim A(1 To 6)
Dim B(-5 To 5)
For I = LBound(A) To UBound(A)
    A(I) = (Rnd(1) * 100)
Next I
For I = LBound(B) To UBound(B)
    B(I) = Int(Rnd(1) * 100) + 1
Next I

'display the arrays before and after the gnomesort
Print "unsorted array: ";: printarray A(): Print
gnomesort A()
Print "  sorted array: ";: printarray A(): Print

Print "unsorted array: ";: printarray B(): Print
gnomesort B()
Print "  sorted array: ";: printarray B(): Print
End

Sub printarray (array())
    'print all the elements in a 1 dimensional array  of any range
    For I = LBound(array) To UBound(array)
        Print array(I);
    Next I
End Sub

Sub gnomesort (array())
    'sort a one dimensional array of any size using gnomesort
    'https://en.wikipedia.org/wiki/Gnome_sort
    I = LBound(array) + 1 'find the lowest element in the array and add 1 for the sorting routine
    J = I + 1
    While I <= UBound(array)
        If array(I - 1) <= array(I) Then
            I = J
            J = J + 1
        Else If array(I - 1) > array(I) Then
                Swap array(I - 1), array(I)
                I = I - 1
                If I = LBound(array) Then
                    I = J
                    J = J + 1
                End If
            End If
        End If
    Wend
End Sub
Reply


Messages In This Thread
GnomeSort - by James D Jarvis - 04-26-2024, 07:52 PM
RE: GnomeSort - by bplus - 04-27-2024, 01:09 AM
RE: GnomeSort - by James D Jarvis - 04-27-2024, 12:49 PM
RE: GnomeSort - by bplus - 04-27-2024, 04:08 PM
RE: GnomeSort - by James D Jarvis - 04-27-2024, 07:53 PM
RE: GnomeSort - by SMcNeill - 04-27-2024, 09:39 PM
RE: GnomeSort - by bplus - 04-29-2024, 02:51 AM
RE: GnomeSort - by SMcNeill - 04-29-2024, 03:34 AM
RE: GnomeSort - by bplus - 04-29-2024, 12:29 PM



Users browsing this thread: 1 Guest(s)