# Gw Temp

## Tutorial - 'Sorting Data' by DarkStorm

An item about Programming Languages posted on

### Blurb

A QBASIC tutorial from DarkStorm that shows you how to use the bubblesort method to sort arrays of data.

### Body

=================================
Writing an EASY sort Algorith
=================================
By DarkStorm

Although it may sound hard to create a simple sort engine, it is actually
suprisingly easy.

In this quick tutorial i will show you how to use the "Bubble" sort algorithm
so called because the values float upwards to their proper positions.

For this example i will make the algorithm sort the numbers stored in an array
into ascending order, it can be used for other things but you would need to change
the sort criteria.

This is an example program written in QBasic so it should work in VBasic and with little
effort convert to other languages: (by the way ' Symbolises a comment)

-----------------------------------------

'Bubble Algorithm Example Program

CLS
DIM numbers(1 to 10) AS INTEGER
'Declare an array with 10 places numbered
'1 to 10
DIM trigger AS INTEGER

PRINT "Enter 10 numbers to sort.."
FOR i = 0 TO 9
INPUT numbers(i)
NEXT i

CLS
FOR i = 0 TO 9
PRINT numbers(i)
'This is simply to show the original
'order of the numbers
NEXT i

PRINT "Sorting..."
DO
trigger = 0
FOR i = 0 TO 8
IF numbers(i) > numbers(i + 1) THEN
SWAP numbers(i), numbers(i + 1)
trigger = 1
END IF
NEXT i
LOOP WHILE trigger = 1

FOR i = 0 TO 9
PRINT numbers(i)
NEXT i
' This displays the sorted numbers...

END

-------------------------------------------

The important part is the:

DO
trigger = 0
FOR i = 0 TO 8
IF numbers(i) > numbers(i + 1) THEN
SWAP numbers(i), numbers(i + 1)
trigger = 1
END IF
NEXT i
LOOP WHILE trigger = 1

The program will loop until trigger = 0, trigger is set to 0 at the start
of the loop and if no variables have to be swapped then the loop ends,
however if a number is bigger then the next number in the array then it is
swapped with that number, trigger is set to one and the program makes another
pass through the array, when everything is sorted the IF statement is no
longer activated an therefore the loop ends.

IF numbers(i) > numbers(i + 1) THEN
That is the sorting criteria if you put...
IF numbers(i) < numbers(i + 1) THEN
Then it would sort in descending order instead, changing this you can get it to
sort text by 1st letter and stuff like that.