46 lines
1.2 KiB
Text
46 lines
1.2 KiB
Text
' FB 1.05.0 Win64
|
|
|
|
Sub quicksort(a() As Double, first As Integer, last As Integer)
|
|
Dim As Integer length = last - first + 1
|
|
If length < 2 Then Return
|
|
Dim pivot As Double = a(first + length\ 2)
|
|
Dim lft As Integer = first
|
|
Dim rgt As Integer = last
|
|
While lft <= rgt
|
|
While a(lft) < pivot
|
|
lft +=1
|
|
Wend
|
|
While a(rgt) > pivot
|
|
rgt -= 1
|
|
Wend
|
|
If lft <= rgt Then
|
|
Swap a(lft), a(rgt)
|
|
lft += 1
|
|
rgt -= 1
|
|
End If
|
|
Wend
|
|
quicksort(a(), first, rgt)
|
|
quicksort(a(), lft, last)
|
|
End Sub
|
|
|
|
Function median(a() As Double) As Double
|
|
Dim lb As Integer = LBound(a)
|
|
Dim ub As Integer = UBound(a)
|
|
Dim length As Integer = ub - lb + 1
|
|
If length = 0 Then Return 0.0/0.0 '' NaN
|
|
If length = 1 Then Return a(ub)
|
|
Dim mb As Integer = (lb + ub) \2
|
|
If length Mod 2 = 1 Then Return a(mb)
|
|
Return (a(mb) + a(mb + 1))/2.0
|
|
End Function
|
|
|
|
Dim a(0 To 9) As Double = {4.4, 2.3, -1.7, 7.5, 6.6, 0.0, 1.9, 8.2, 9.3, 4.5}
|
|
quicksort(a(), 0, 9)
|
|
Print "Median for all 10 elements : "; median(a())
|
|
' now get rid of final element
|
|
Dim b(0 To 8) As Double = {4.4, 2.3, -1.7, 7.5, 6.6, 0.0, 1.9, 8.2, 9.3}
|
|
quicksort(b(), 0, 8)
|
|
Print "Median for first 9 elements : "; median(b())
|
|
Print
|
|
Print "Press any key to quit"
|
|
Sleep
|