Need a sorting routine
#9
(03-04-2023, 09:00 AM)mdijkens Wrote:
Code: (Select All)
Type DATATYPE
  a As Integer
  b As Integer
  c As Integer
End Type

ReDim Shared SortedList(32767) As DATATYPE

Randomize Timer
For x% = 0 To UBound(SortedList)
  SortedList(x%).a = Int(Rnd * 32768)
Next x%
t# = Timer(.001)
QSort 0, UBound(SortedList)
t2# = Timer(.001)
For x% = 0 To UBound(SortedList)
  Print SortedList(x%).a;
Next x%
Print: Print Using "#.### sec"; t2# - t#
End


Sub QSort (leftN As Long, rightN As Long)
  Dim pivot As Long, leftNIdx As Long, rightNIdx As Long
  leftNIdx = leftN
  rightNIdx = rightN
  If (rightN - leftN) > 0 Then
    pivot = (leftN + rightN) / 2
    While (leftNIdx <= pivot) And (rightNIdx >= pivot)
      While SortedList(leftNIdx).a < SortedList(pivot).a And (leftNIdx <= pivot)
        leftNIdx = leftNIdx + 1
      Wend
      While SortedList(rightNIdx).a > SortedList(pivot).a And (rightNIdx >= pivot)
        rightNIdx = rightNIdx - 1
      Wend
      Swap SortedList(leftNIdx), SortedList(rightNIdx)
      leftNIdx = leftNIdx + 1
      rightNIdx = rightNIdx - 1
      If (leftNIdx - 1) = pivot Then
        rightNIdx = rightNIdx + 1
        pivot = rightNIdx
      ElseIf (rightNIdx + 1) = pivot Then
        leftNIdx = leftNIdx - 1
        pivot = leftNIdx
      End If
    Wend
    QSort leftN, pivot - 1
    QSort pivot + 1, rightN
  End If
End Sub

Holy heck this routine is fast! It takes 5000 values before it even begins to show a time of .001 sec to complete.
Software and cathedrals are much the same — first we build them, then we pray.
QB64 Tutorial
Reply


Messages In This Thread
Need a sorting routine - by TerryRitchie - 03-04-2023, 06:53 AM
RE: Need a sorting routine - by mnrvovrfc - 03-04-2023, 08:58 AM
RE: Need a sorting routine - by TerryRitchie - 03-04-2023, 05:34 PM
RE: Need a sorting routine - by mdijkens - 03-04-2023, 09:00 AM
RE: Need a sorting routine - by TerryRitchie - 03-04-2023, 06:16 PM
RE: Need a sorting routine - by bplus - 03-04-2023, 10:02 AM
RE: Need a sorting routine - by RhoSigma - 03-04-2023, 10:03 AM
RE: Need a sorting routine - by SMcNeill - 03-04-2023, 10:46 AM
RE: Need a sorting routine - by SMcNeill - 03-04-2023, 06:14 PM
RE: Need a sorting routine - by TerryRitchie - 03-04-2023, 06:30 PM
RE: Need a sorting routine - by SMcNeill - 03-04-2023, 06:27 PM
RE: Need a sorting routine - by SMcNeill - 03-04-2023, 06:47 PM
RE: Need a sorting routine - by TerryRitchie - 03-04-2023, 06:52 PM
RE: Need a sorting routine - by SMcNeill - 03-04-2023, 07:14 PM
RE: Need a sorting routine - by Dimster - 03-05-2023, 02:49 PM
RE: Need a sorting routine - by TempodiBasic - 03-11-2023, 02:26 AM
RE: Need a sorting routine - by TempodiBasic - 03-11-2023, 02:34 AM



Users browsing this thread: 8 Guest(s)