RosettaCodeData/Task/Sort-an-integer-array/FreeBASIC/sort-an-integer-array.basic

59 lines
1.6 KiB
Plaintext

' version 11-03-2016
' compile with: fbc -s console
#Include Once "crt/stdlib.bi" ' needed for qsort subroutine
' Declare Sub qsort (ByVal As Any Ptr, <== point to start of array
' ByVal As size_t, <== size of array
' ByVal As size_t, <== size of array element
' ByVal As Function(ByVal As Any Ptr, ByVal As Any Ptr) As Long) <== callback function
' declare callback function with Cdecl to ensures that the parameters are passed in the correct order
'
' size of long: 4 bytes on 32bit OS, 8 bytes on 64bit OS
' ascending
Function callback Cdecl (ByVal element1 As Any Ptr, ByVal element2 As Any Ptr) As Long
Function = *Cast(Long Ptr, element1) - *Cast(Long Ptr, element2)
End Function
' Function callback Cdecl (ByVal element1 As Any Ptr, ByVal element2 As Any Ptr) As Long
' Dim As Long e1 = *Cast(Long Ptr, element1)
' Dim As Long e2 = *Cast(Long Ptr, element2)
' Dim As Long result = Sgn(e1 - e2)
' If Sgn(e1) = -1 And Sgn(e2) = -1 Then result = -result
' Function = result
' End Function
' ------=< MAIN >=------
Dim As Long i, array(20)
Dim As Long lb = LBound(array)
Dim As Long ub = UBound(array)
For i = lb To ub ' fill array
array(i) = 10 - i
Next
Print
Print "unsorted array"
For i = lb To ub ' display array
Print Using "###";array(i);
Next
Print : Print
' sort array
qsort(@array(lb), ub - lb +1, SizeOf(array), @callback)
Print "sorted array"
For i = lb To ub ' show sorted array
Print Using "###";array(i);
Next
Print
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End