#COMPILE EXE
#DIM ALL

FUNCTION PBMAIN() AS LONG
    LOCAL arr(100) AS LONG
    LOCAL output(100) AS LONG
    LOCAL counts(200) AS LONG
    LOCAL n AS LONG
    LOCAL i AS LONG
    LOCAL j AS LONG
    LOCAL max_val AS LONG
    LOCAL min_val AS LONG
    LOCAL range_val AS LONG
    LOCAL bucket(100) AS LONG
    LOCAL bsize(10) AS LONG
    LOCAL b_idx AS LONG
    LOCAL bucket_size AS LONG
    LOCAL bucket_idx(10) AS LONG
    LOCAL num_buckets AS LONG
    LOCAL temp_str AS STRING
    LOCAL temp_val AS LONG

    PRINT "Counting Sort and Bucket Sort"

    n = 15
    arr(0) = 4: arr(1) = 2: arr(2) = 2: arr(3) = 8: arr(4) = 3
    arr(5) = 3: arr(6) = 1: arr(7) = 5: arr(8) = 7: arr(9) = 6
    arr(10) = 3: arr(11) = 4: arr(12) = 9: arr(13) = 2: arr(14) = 5

    max_val = 0
    FOR i = 0 TO n - 1
        IF arr(i) > max_val THEN max_val = arr(i)
    NEXT i

    FOR i = 0 TO max_val
        counts(i) = 0
    NEXT i
    FOR i = 0 TO n - 1
        counts(arr(i)) = counts(arr(i)) + 1
    NEXT i
    FOR i = 1 TO max_val
        counts(i) = counts(i) + counts(i - 1)
    NEXT i
    FOR i = n - 1 TO 0 STEP -1
        temp_val = arr(i)
        counts(temp_val) = counts(temp_val) - 1
        output(counts(temp_val)) = temp_val
    NEXT i

    PRINT "Counting sort result:"
    FOR i = 0 TO n - 1
        PRINT STR$(output(i))
    NEXT i

    PRINT "Done."
    FUNCTION = 0
END FUNCTION
