home *** CD-ROM | disk | FTP | other *** search
/ QBasic & Borland Pascal & C / Delphi5.iso / Basic / Q_BASIC.450 / SORTDEMO.BAS (.txt) < prev    next >
Encoding:
QuickBASIC Tokenized Source  |  1989-08-07  |  21.2 KB  |  353 lines

  1. RandInt
  2. lower
  3. Upper
  4. BoxInit0
  5. BubbleSortY
  6. CheckScreen+
  7. @    DrawFrame
  8. TopSideF
  9. BottomSide
  10. LeftSide
  11.     RightSide
  12. ElapsedTime
  13. CurrentRow
  14. ExchangeSort
  15. HeapSort
  16. Initialize8
  17. InsertionSort
  18. PercolateDown
  19. MaxLevel`
  20. PercolateUp~
  21. PrintOneBarK
  22. @    QuickSort
  23. Reinitialize
  24. @    ShellSort
  25. SortMenu
  26. SwapBarsm
  27. ToggleSound'
  28. Column
  29. SortType
  30. Length
  31. ColorVal
  32.     BarString
  33. FALSE
  34. LEFTCOLUMNT
  35. NUMOPTIONS
  36. NUMSORTS
  37.     SortArray%
  38. SortBackup
  39. OptionTitle
  40.     StartTime
  41. Foreground
  42. Background
  43. NoSoundB
  44. Pause
  45.     Selection
  46. MaxRow
  47. InitRowU
  48.     MaxColors
  49. GetRow
  50. MonoTrap/
  51. RowTrap
  52. Limit
  53. Switch8
  54. ULEFT
  55. URIGHT
  56. LLEFT
  57. LRIGHT
  58. VERTICAL
  59. HORIZONTAL
  60. FrameWidth
  61. FORMAT
  62. SmallestRow
  63.     TempArray
  64. MaxIndex
  65. Index
  66.     BarLength
  67. TempVal
  68. TempLength
  69. Child
  70. Parent
  71.     RandIndex
  72.     Partition
  73. Offset
  74. Escape
  75. Option
  76. Choice
  77. Checffff
  78. ! SORTDEMO 
  79.  This program graphically demonstrates six common sorting algorithms.  It=
  80.  prints 25 or 43 horizontal bars, all of different lengths and all in random
  81. ! SORTDEMO 
  82.  This program graphically demonstrates six common sorting algorithms.  It=
  83.  prints 25 or 43 horizontal bars, all of different lengths and all in random
  84.  order, then sorts the bars from smallest to longest.n
  85.  The program also uses SOUND statements to generate different pitches,
  86.  depending on the location of the bar being printed. Note that the SOUND
  87.  statements delay the speed of each sorting algorithm so you can followD
  88.  the progress of the sort.  Therefore, the times shown are for comparison
  89.  only. They are not an accurate measure of sort speed.
  90.  If you use these sorting routines in your own programs, you may noticeo
  91.  a difference in their relative speeds (for example, the exchangen
  92.  sort may be faster than the shell sort) depending on the number of
  93.  elements to be sorted and how "scrambled" they are to begin with.
  94.  Default type integer.
  95.  Declare FUNCTION and SUB procedures, and the number and type of arguments:=
  96.  Define the data type used to hold the information for each colored bar:
  97.  Bar length (the element comparedr
  98.  in the different sorts)
  99.  Bar color
  100.  The bar (a string of 43 characters)
  101.  Declare global constants:
  102.  Declare global variables, and allocate storage space for them.  SortArray
  103.  and SortBackup are both arrays of the data type SortType defined above:
  104.  Data statements for the different options printed in the sort menu:
  105.  Insertion, Bubble, Heap, Exchange, Shell, Quick,
  106.  Toggle Sound, , <   (Slower), >   (Faster)
  107.  Begin logic of module-level code:
  108.  Initialize data values.
  109.  Print sort menu.v
  110.  Restore original number of rows.
  111.  Restore default color
  112.  GetRow, MonoTrap, and RowTrap are error-handling routines invoked by
  113.  the CheckScreen SUB procedure.  GetRow determines whether the program
  114.  started with 25, 43, or 50 lines.  MonoTrap determines the currentr
  115.  video adapter is monochrome.  RowTrap sets the maximum possible
  116.  number of rows (43 or 25).e
  117. RandInt
  118. = RandInt% 
  119.    Returns a random integer greater than or equal to the Lower parameter
  120.    and less than or equal to the Upper parameter. 
  121. BoxInit
  122. = BoxInit 
  123.  Calls the DrawFrame procedure to draw the frame around the sort menu,
  124.  then prints the different options stored in the OptionTitle array.n
  125. QUICKBASIC SORTING DEMO"
  126.  Don't print the last option (> Faster) if the length of the Pause
  127.  is down to 1 clock tick:i
  128.  Toggle sound on or off, then print the current value for NoSound:
  129. Type first character of"
  130. choice ( I B H E S Q T < > )
  131. or ESC key to end program: "
  132. BubbleSort
  133. = BubbleSort 
  134.  The BubbleSort algorithm cycles through SortArray, comparing adjacent
  135.  elements and swapping pairs that are out of order.  It continues to
  136.  do this until no pairs are swapped.
  137.  Two adjacent elements are out of order, so swap their values=
  138.  and redraw those two bars:o
  139.  Sort on next pass only to where the last switch was made:
  140. CheckScreen
  141. = CheckScreen 
  142.  Checks for type of monitor (VGA, EGA, CGA, or monochrome) and
  143.  starting number of screen lines (50, 43, or 25).n
  144.  Try locating to the 50th row; if that fails, try the 43rd. Finally,
  145.  if that fails, the user was using 25-line mode:
  146.  Try a SCREEN 1 statement to see if the current adapter has colorl
  147.  graphics; if that causes an error, reset MaxColors to 2:a
  148.  See if 43-line mode is accepted; if not, run this program in 25-line
  149.  mode:
  150.  Turn off error trapping.t
  151. DrawFrame
  152. = DrawFrame 
  153.    Draws a rectangular frame using the high-order ASCII characters 
  154.  (201) ,
  155.  (187) , 
  156.  (200) , 
  157.  (188) , 
  158.  (186) , and 
  159.  (205). The parameters
  160.    TopSide, BottomSide, LeftSide, and RightSide are the row and column
  161.    arguments for the upper-left and lower-right corners of the frame.n
  162. ElapsedTime
  163. = ElapsedTime 
  164.  Prints seconds elapsed since the given sorting routine started.
  165.  Note that this time includes both the time it takes to redraw the
  166.  bars plus the pause while the SOUND statement plays a note, and
  167.  thus is not an accurate indication of sorting speed.a
  168.   &###.### seconds  
  169.  Print current selection and number of seconds elapsed in=
  170.  reverse video:s
  171.  Sound off, so just pause.
  172.  Sound on, so play a note whilee
  173.  pausing.
  174.  Restore regular foreground andl
  175.  background colors.e
  176. ExchangeSort
  177. = ExchangeSort 
  178.    The ExchangeSort compares each element in SortArray - starting with
  179.    the first element - with every following element.  If any of thei
  180.    following elements is smaller than the current element, it is exchanged
  181.    with the current element and the process is repeated for the next
  182.    element in SortArray.
  183.  Found a row shorter than the current row, so swap those
  184.  two array elements:
  185. HeapSort
  186. = HeapSort 
  187.   The HeapSort procedure works by calling two other procedures - PercolateUp
  188.   and PercolateDown.  PercolateUp turns SortArray into a "heap," which has
  189.   the properties outlined in the diagram below:a
  190.  SortArray(1) 
  191.  SortArray(2)
  192.  SortArray(3)
  193.      SortArray(4)   SortArray(5)   SortArray(6)  SortArray(7)e
  194.  ...   ...
  195.  ...   ...
  196.  ...  ...
  197.  ...S
  198.   where each "parent node" is greater than each of its "child nodes"; fors
  199.   example, SortArray(1) is greater than SortArray(2) or SortArray(3), 
  200.   SortArray(3) is greater than SortArray(6) or SortArray(7), and so forth.
  201.   Therefore, once the first FOR...NEXT loop in HeapSort is finished, the
  202.   largest element is in SortArray(1).T
  203.   The second FOR...NEXT loop in HeapSort swaps the element in SortArray(1)
  204.   with the element in MaxRow, rebuilds the heap (with PercolateDown) for
  205.   MaxRow - 1, then swaps the element in SortArray(1) with the element in
  206.   MaxRow - 1, rebuilds the heap for MaxRow - 2, and continues in this way
  207.   until the array is sorted.
  208. Initialize
  209. = Initialize 
  210.  Initializes the SortBackup and OptionTitle arrays.  It also calls the
  211.  CheckScreen, BoxInit, and RandInt% procedures.a
  212.  Check for monochrome or EGA and set
  213.  maximum number of text lines.
  214.  Seed the random-number generator.
  215.  Call RandInt% to find a random element in TempArray between 1
  216.  and MaxIndex, then assign the value in that element to BarLength:
  217.  Overwrite the value in TempArray(Index) with the value in
  218.  TempArray(MaxIndex) so the value in TempArray(Index) is
  219.  chosen only once:
  220.  Decrease the value of MaxIndex so that TempArray(MaxIndex) can't:
  221.  be chosen on the next pass through the loop:r
  222.  Assign the BarLength value to the .Length element, then store
  223.  a string of BarLength block characters (ASCII 223: 
  224. ) in thee
  225.  .BarString element:
  226.  Store the appropriate color value in the .ColorVal element:
  227.  Read SORT DEMO menu options and store
  228.  them in the OptionTitle array.s
  229.  Assign values in SortBackup to SortArray and draw
  230.  unsorted bars on the screen.a
  231.  Initialize Pause to 2 clock ticks (@ 1/9 second).
  232.  Draw frame for the sort menu and print options.
  233. InsertionSort
  234. = InsertionSort 
  235.    The InsertionSort procedure compares the length of each successive=
  236.    element in SortArray with the lengths of all the preceding elements.
  237.    When the procedure finds the appropriate place for the new element, it
  238.    inserts the element in its new place, and moves all the other elements
  239.    down one place.
  240.  As long as the length of the J-1st element is greater than the=
  241.  length of the original element in SortArray(Row), keep shifting
  242.  the array elements down:l
  243.  Print the new bar.
  244.  Print the elapsed time.
  245.  Otherwise, exit the FOR...NEXT loop:r
  246.  Insert the original value of SortArray(Row) in SortArray(J):i
  247. PercolateDown
  248. = PercolateDown 
  249.    The PercolateDown procedure restores the elements of SortArray from 1 to=
  250.    MaxLevel to a "heap" (see the diagram with the HeapSort procedure).
  251.  Move the value in SortArray(1) down the heap until it has
  252.  reached its proper node (that is, until it is less than its parent=
  253.  node or until it has reached MaxLevel, the bottom of the current heap):
  254.  Get the subscript for the child node.
  255.  Reached the bottom of the heap, so exit this procedure:
  256.  If there are two child nodes, find out which one is bigger:
  257.  Move the value down if it is still not bigger than either one of 
  258.  its children:
  259.  Otherwise, SortArray has been restored to a heap from 1 to MaxLevel,p
  260.  so exit:e
  261. PercolateUp
  262. = PercolateUp 
  263.    The PercolateUp procedure converts the elements from 1 to MaxLevel in
  264.    SortArray into a "heap" (see the diagram with the HeapSort procedure).
  265.  Move the value in SortArray(MaxLevel) up the heap until it has=
  266.  reached its proper node (that is, until it is greater than either
  267.  of its child nodes, or until it has reached 1, the top of the heap):=
  268.  Get the subscript for the parent node. 
  269.  The value at the current node is still bigger than the value at
  270.  its parent node, so swap these two array elements: 
  271.  Otherwise, the element has reached its proper place in the heap,
  272.  so exit this procedure:
  273. PrintOneBar
  274. = PrintOneBar 
  275.   Prints SortArray(Row).BarString at the row indicated by the Row
  276.   parameter, using the color in SortArray(Row).ColorVal.
  277. QuickSort
  278. = QuickSort 
  279.    QuickSort works by picking a random "pivot" element in SortArray, then=
  280.    moving every element that is bigger to one side of the pivot, and every
  281.    element that is smaller to the other side.  QuickSort is then callede
  282.    recursively with the two subdivisions created by the pivot.  Once the
  283.    number of elements in a subdivision reaches two, the recursive calls end
  284.    and the array is sorted.s
  285.  Only two elements in this subdivision; swap them if they are out of
  286.  order, then end recursive calls:i
  287.  Pick a pivot element at random, then move it to the end: 
  288.  Move in from both sides towards the pivot element:e
  289.  If we haven't reached the pivot element, it means that two
  290.  elements on either side are out of order, so swap them:
  291.  Move the pivot element back to its proper place in the array:
  292.  Recursively call the QuickSort procedure (pass the smallera
  293.  subdivision first to use less stack space):
  294. Reinitialize
  295. = Reinitialize 
  296.    Restores the array SortArray to its original unsorted state, then
  297.    prints the unsorted color bars.
  298. ShellSort
  299. = ShellSort 
  300.   The ShellSort procedure is similar to the BubbleSort procedure.  However,=
  301.   ShellSort begins by comparing elements that are far apart (separated byr
  302.   the value of the Offset variable, which is initially half the distance
  303.   between the first and last element), then comparing elements that aree
  304.   closer together (when Offset is one, the last iteration of this procedure
  305.   is merely a bubble sort).s
  306.  Set comparison offset to half the number of records in SortArray:
  307.  Loop until offset gets to zero.
  308.  Assume no switches at this offset..
  309.  Compare elements and switch ones out of order:c
  310.  Sort on next pass only to where last switch was made:
  311.  No switches at last offset, try one half as big:m
  312. SortMenu
  313. = SortMenu 
  314.    The SortMenu procedure first calls the Reinitialize procedure to make
  315.    sure the SortArray is in its unsorted form, then prompts the user toe
  316.    make one of the following choices:t
  317.  * One of the sorting algorithms
  318.  * Toggle sound on or offo
  319.  * Increase or decrease speedh
  320.  * End the program
  321.  Create a string consisting of all legal choices:=
  322. IBHESQ><T"
  323.  Make the cursor visible:E
  324.  Get the user's choice and see
  325.  if it's one of the menu options.s
  326.  User chose one of the sorting procedures:
  327.  Rescramble the bars.i
  328.  Make the cursor invisible.e
  329.  Set reverse-video values.
  330.  Record the starting time.
  331.  Branch to the appropriate procedure depending on the key typed:
  332.  Decrease pause length to speed up sorting time, then redraw
  333.  the menu to clear any timing results (since they won't compare:
  334.  with future results):
  335.  Increase pause length to slow down sorting time, then redrawr
  336.  the menu to clear any timing results (since they won't compare
  337.  with future results):
  338.  User pressed ESC, so exit this procedure and return to 
  339.  module level:
  340.  Invalid key
  341.  Turn off reverse video.
  342.  Print final time.
  343. SwapBars
  344. = SwapBars 
  345.    Calls PrintOneBar twice to switch the two bars in Row1 and Row2,=
  346.    then calls the ElapsedTime procedure.
  347. ToggleSound
  348. = ToggleSound 
  349.    Reverses the current value for NoSound, then prints that value next
  350.    to the "Toggle Sound" option on the sort menu.r
  351. : OFF"
  352. : ON "
  353.