Ooops
October 29, 2020, 02:08:39 AM

Author Topic: Sort Data While Loading It  (Read 564 times)

Offline bplus

  • Full Member
  • ***
  • Posts: 146
Sort Data While Loading It
« on: November 04, 2019, 02:09:31 AM »
This method can be handy, meant for smallish arrays.
Code: [Select]
' Load and sort data at same time.bas SmallBASIC 0.12.13 (B+=MGA) 2019-11-03
' 2019-11-03 trans to SmallBASIC from QB64 from
'_TITLE "Load and sort to array at same time" 'B+ 2019-10-26
' 2019-10-27 edited 2x with Steve's improvements thanks Steve!
' 2019-11-03 mod for name score data file
' 2019-11-03 cut 4 lines!
'
'!!!!!!!!!!!!!!!! What is cool about SmallBASIC is that the following is not needed!!!
' TYPE dat
'     name AS STRING
'    score AS INTEGER
' END TYPE

DIM d(1 TO 100) 'dimensioned to something known to be > data lines
OPEN "name_score.dat" FOR INPUT AS #1
WHILE EOF(1) = 0
  INPUT #1, n, s
  IF TRIM(n) <> "" THEN
    i = i + 1
    PRINT right(space(10) + n, 10) + ", " + left(s + space(10), 10)
    FOR j = 1 TO i - 1
      IF s > d(j).score THEN
        FOR k = i TO j + 1 STEP -1
          d(k) = d(k - 1)
        NEXT
        EXIT FOR
      END IF
    NEXT
    d(j).score = s: d(j).name = n
  END IF
WEND
CLOSE #1
PRINT: PRINT " and sorted while loading array:"
FOR j = 1 TO i
  ? right(space(10) + d(j).name, 10) + ", " + left(d(j).score + space(10), 10)
NEXT

EDIT: Oh heck found an improvement to cut 4 lines.

demo output

 

SimplePortal 2.3.6 © 2008-2014, SimplePortal