Navigation

    Fuze Arena Logo
    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Popular
    • Users
    • Groups
    • Help
    • Discord

    Sorting an Array of Strings

    Beginners
    1
    1
    140
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • T
      tony7059 last edited by tony7059

      I'm new to Fuze, so decided to play with how to sort an array of strings. It just uses a simple bubble sort routine, assuming a simple short list of strings you might want to order. Note that I wasn't sure how scoping worked in Fuze so got paranoid about how to make sure variables were local and the there would be some weird clash between returns from functions ...

      /*
      Compare numbers.
      Returns 0 if equal, 1 if a is larger, or -1 if a is smaller.
      */
      function compareNum( a, b )
          int compareNum = 0
          if a > b then
              compareNum = 1
          else
              if a < b then compareNum = -1 endif
          endif
      return compareNum
      
      /*
      Compare two strings.
      Return 0 if strings are equal, -1 if str1 is before, or 1 if str1 comes after.
      Uses: compareNum( a, b)
      */
      function compareStr(str1, str2)
          int compareStr = 0
          // Need the smallest length to stay in bounds because
          // we're comparing each set of characters between strings.
          int bounds = min( len( str1), len( str2 ) )
          for i = 0 to bounds loop
              compareStr = compareNum( charval( str1[i] ), charval( str2[i] )
              if compareStr != 0 then break endif
          repeat
      return compareStr
      
      /*
      Sort an array of strings.  The strings are sorted "in place" (in the original array, as opposed to a copy that's returned.
      */
      function sortStrs( ref list )
          int items = len( list )
          
          // BUBBLE SORT ROUTINE...
          for i = 0 to items loop
              for j  = 0 to items loop
                  // Compare adjacent strings and swap when necessary...
                  if compareStr( list[j], list[j+1] ) == 1 then
                      string temp = list[j+1]
                      list[j+1] = list[j]
                      list[j] = temp
                   endif
              repeat
          repeat
      return void
      
      // Simple Test:
      inventory = [
      "uvw",
      "abc",
      "wxy",
      "tuv",
      "bcd",
      "tuv"
      ]
      
      sortStrs( inventory )
      loop
      clear()
      print( inventory )
      update()
      repeat
      

      Hope this is useful or educational. Try Download ID of 29873MND18.

      1 Reply Last reply Reply Quote 2
      • First post
        Last post