| Sample Shell Sort program in QBSeptember 24 2002 at 9:58 AM | Solitaire (no login) |
Response to Shell Sort, Bubble Sort, Sorting in general |
| The Shell Sort is suitable for lists over 30 items. It uses an interval called a "gap" to compare distant items first, and makes its way down to nearby items. It divides the list in half, comparing and swapping corresponding items between two halves of the list, and keeps dividing the list in half until only two items remain. Lists fewer than 30 items would take more swaps than a Bubble Sort to finish, but larger lists would need fewer swaps.
This example first creates an array of 35 random numbers between 1 - 100 and displays the original unsorted list. Then it uses a Shell Sort to arrange them in order and displays the sorted list.
CLS
DIM doneflag AS INTEGER
DIM gap AS INTEGER, temp AS INTEGER, x AS INTEGER
DIM mArnum(1 TO 35) AS SINGLE
CONST FALSE = 0, TRUE = NOT FALSE
PRINT "Random unsorted list of 35 numbers:"
PRINT
RANDOMIZE TIMER
FOR x = 1 TO 35
mArnum(x) = INT(RND * 100) + 1
PRINT mArnum(x);
NEXT x
gap = INT(35 / 2)
DO WHILE gap >= 1
DO
doneflag = TRUE
FOR x = 1 TO 35 - gap
IF mArnum(x) > mArnum(x + gap) THEN
temp = mArnum(x)
mArnum(x) = mArnum(x + gap)
mArnum(x + gap) = temp
doneflag = FALSE
END IF
NEXT x
LOOP UNTIL doneflag = TRUE
gap = INT(gap / 2)
LOOP
PRINT : PRINT : PRINT
PRINT "Same list of numbers after a Shell Sort: "
PRINT
FOR x = 1 TO 35
PRINT mArnum(x);
NEXT x
END
|
| | Responses |
|
|