# Sorting an Array

February 19 2004 at 10:45 AM

How can I sort an Array?

For MUCH more detail on sorting, see
http://www.network54.com/Forum/182035/message/1032554896

And the Visual Basic forum has a thread that really looks at all possible sorts. It kind of applies to QBasic.

The program below shows the "selection sort" a popular and practical sort for small arrays such as often come up in games and non-commercial database programs.

It also shows the "bubble sort", a sort that has no practical value unless you are dealing with arrays that are already nearly sorted. For example, if you were keeping an index of employees sorted by last name and you just added a few new employees at the end of the index, the bubble sort would be good. It is slightly slower than the selection sort for completely unsorted arrays, as you can see by trying the program.

For a more complete collection of sorting methods, see
http://www.network54.com/Hide/Forum/message?forumid=182035&messageid=1032554896

In that thread, the superfast (but difficult to code without copying it from somewhere else) "quicksort" is given. This is good for large arrays.

Mac

CLS
PRINT "Illustration of the Selection and Bubble sorts"

RANDOMIZE TIMER
ASize = 250
DIM a(ASize) AS INTEGER

FOR i = 1 TO ASize: a(i) = INT(RND * 32000): NEXT i
LOCATE , , 1
PRINT "Press button to see how fast the Selection Sort is: ";
PRINT INPUT\$(1)

'======================= Selection Sort
FOR i = 1 TO ASize - 1
FOR j = i TO ASize
IF a(i) > a(j) THEN SWAP a(i), a(j)
NEXT j
NEXT i
'=======================

PRINT "Done!"
GOSUB CheckIt

FOR i = 1 TO ASize: a(i) = INT(RND * 32000): NEXT i
LOCATE , , 1
PRINT "Press button to see how fast the Bubble Sort is: ";
PRINT INPUT\$(1)

'======================= Bubble Sort
LastOne = ASize - 1
DO
Bubbles = 0
FOR i = 1 TO LastOne
IF a(i) > a(i + 1) THEN SWAP a(i), a(i + 1): Bubbles = 1: LastOne = i
NEXT i
LOOP WHILE Bubbles = 1
'=======================

PRINT "Done!"
GOSUB CheckIt
SYSTEM

CheckIt:
FOR i = 1 TO ASize - 1
IF a(i) > a(i + 1) THEN
PRINT "Sort failed! Bug!"
STOP
END IF
NEXT i
RETURN

 This message has been edited by iorr5t on Jun 16, 2007 11:12 AMThis message has been edited by iorr5t on Jul 10, 2006 7:00 AM

 Respond to this message
anonymous

# SORTDEMO.BAS

May 14 2005, 5:51 PM
 QuickBasic has an example file named SORTDEMO.BAS (in EXAMPLES folder) that demonstrates various sorting algorithms (with user interfaces and animated representations of data being sorted). Even better, each sorting algorithms are in their own subroutine, so we can copy the codes easily.
 Respond to this message
anonymous