Advertisement
Dr_Davenstein

crt qsort example

Apr 16th, 2025
254
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
FreeBasic 1.09 KB | Source Code | 0 0
  1. #include once "crt.bi"
  2.  
  3. randomize timer
  4.  
  5. type character_struct
  6.    
  7.     as string * 10 name
  8.    
  9.     as integer yPosition
  10.    
  11. end type
  12.  
  13.  
  14.  
  15. declare function char_sort_callback cdecl ( byval elm1 as any ptr, byval elm2 as any ptr ) as integer
  16.  
  17.  
  18.  
  19. dim as character_struct characters(10)
  20.  
  21. print "NOT SORTED..."
  22. for i as integer = 0 to ubound(characters)
  23.    
  24.     characters(i).yPosition = int(rnd*10000)
  25.     print characters(i).yPosition
  26.    
  27. next
  28.  
  29.  
  30.  
  31. 'here's how to call the crt qsort on a custom type
  32. qsort( @characters(0), ubound(characters)+1, sizeof(character_struct), @char_sort_callback() )
  33.  
  34. print
  35. print "SORTED..."
  36. for i as integer = 0 to ubound(characters)
  37.    
  38.     print characters(i).yPosition
  39.    
  40. next
  41.  
  42. sleep
  43.  
  44.  
  45.  
  46. 'here's the meat of it...
  47. 'we're sorting based on the "yPosition" variable in the character type,
  48. 'which will sort every element of the whole array in turn.
  49. function char_sort_callback cdecl ( byval elm1 as any ptr, byval elm2 as any ptr ) as integer
  50.        
  51.     return sgn( (cptr(character_struct ptr, elm1)->yPosition) - (cptr(character_struct ptr, elm2)->yPosition) )
  52.        
  53. end function
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement