TGC Codebase Backup



QuickSort Example by TheOneRing

2nd Oct 2003 9:34
Summary

Example of a QuickSort function.



Description

This is a simple example of a QuickSort function. This snippet first populates a 10-element array with out-of-order numbers. These numbers are displayed. Then the array is sorted, and the new sorted array is then shown on the screen.



Code
                                    ` This code was downloaded from The Game Creators
                                    ` It is reproduced here with full permission
                                    ` http://www.thegamecreators.com
                                    
                                    dim GeneralArray(10) as integer

`---------------------------------------------------------------
` Read the data into the array. Notice the data is out of order.
`---------------------------------------------------------------
restore __inline_data

for index = 0 to 9
   read tmp
   GeneralArray(index) = tmp
next index

`-------------------------
` Show the unsorted array.
`-------------------------
print "Here is the original array:"
for index = 0 to 9
   print "INDEX " + str$(index) + ": " + str$(GeneralArray(index))
next index

`--------------------------------
` Sort the array using QuickSort.
`--------------------------------
QuickSort(0, 9)

`-----------------------
` Show the sorted array.
`-----------------------
print : print "Here is the new sorted array:"
for index = 0 to 9
   print "INDEX " + str$(index) + ": " + str$(GeneralArray(index))
next index

suspend for key
end


function QuickSort(Lower, Upper)

   pivot as integer

   Left = Lower
   Right = Upper
   pivot = GeneralArray(Left)

   while Left < Right
      while (GeneralArray(Right) >= pivot) and (Left < Right)
         dec Right
      endwhile

      if Right <> Left
         GeneralArray(Left) = GeneralArray(Right)
         inc Left
      endif

      while (GeneralArray(Left) <= pivot) and (Left < Right)
         inc Left
      endwhile

      if Right <> Left
         GeneralArray(Right) = GeneralArray(Left)
         dec Right
      endif
   endwhile

   GeneralArray(Left) = pivot
   pivot = Left

   if Lower < pivot then QuickSort(Lower, pivot - 1)
   if Upper > pivot then QuickSort(pivot + 1, Upper)

endfunction

__inline_data:
data 2, 4, 6, 8, 1, 3, 5, 7, 9