QBasic Program to Sort Numbers in Ascending Order

Write a program to sort numbers in ascending order in QBasic.

For example,

Input
1 5 4 3 7 8 9
Output
1 3 4 5 7 8 9

Steps

  1. First, the user enters the size of array/list. Let it be n.
  2. After that, the user is asked to enter n numbers.
  3. Then we sort the input numbers using bubble sort.
  4. After that, we print the sorted array/list on the screen.
CLS

' enter number of numbers you wish to input
INPUT "Enter size of list of numbers: ", n
DIM lst(1 TO n)
PRINT "Enter "; n; " numbers"
FOR i = 1 TO n
    INPUT lst(i)
NEXT i

' displaying input list
PRINT "INPUT NUMBERS:"
FOR i = 1 TO n
    PRINT lst(i);
NEXT i

' sorting lst in ascending order
' using bubble sort
FOR i = 1 TO n
    FOR j = i + 1 TO n
        IF lst(i) > lst(j) THEN
            SWAP lst(i), lst(j)
        END IF
    NEXT j
NEXT i

' displaying output list
PRINT ""
PRINT "INPUT NUMBERS IN SORTED ORDER:"
FOR i = 1 TO n
    PRINT lst(i);
NEXT i

END

Output

output 1

Qbasic Program to Sort Numbers in Ascending Order using Subroutine

DECLARE SUB sort(lst(), n AS INTEGER)

CLS
' enter number of numbers you wish to input
INPUT "Enter size of list of numbers: ", n
DIM lst(1 TO n)
PRINT "Enter "; n; " numbers"
FOR i = 1 TO n
    INPUT lst(i)
NEXT i

' displaying input list
PRINT "INPUT NUMBERS:"
FOR i = 1 TO n
    PRINT lst(i);
NEXT i

CALL sort(lst(), n)

' displaying output list
PRINT ""
PRINT "INPUT NUMBERS IN SORTED ORDER:"
FOR i = 1 TO n
    PRINT lst(i);
NEXT i


END

' sort subroutine to sort numbers in lst in ascending order
' n is the size of lst
SUB sort (lst(), n AS INTEGER)
    ' sorting lst in ascending order
    ' using bubble sort
    FOR i = 1 TO n
        FOR j = i + 1 TO n
            IF lst(i) > lst(j) THEN
                SWAP lst(i), lst(j)
            END IF
        NEXT j
    NEXT i
END SUB

Output

output 2

Read

Leave a Comment

Your email address will not be published. Required fields are marked *