04-26-2024, 07:52 PM
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