Sorting algorithms/Counting sort: Difference between revisions
Content deleted Content added
Added FreeBASIC |
|||
Line 647:
end program test</lang>
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
Function findMax(array() As Integer) As Integer
Dim length As Integer = UBound(array) - LBound(array) + 1
If length = 0 Then Return 0 '' say
If length = 1 Then Return array(LBound(array))
Dim max As Integer = LBound(array)
For i As Integer = LBound(array) + 1 To UBound(array)
If array(i) > max Then max = array(i)
Next
Return max
End Function
Function findMin(array() As Integer) As Integer
Dim length As Integer = UBound(array) - LBound(array) + 1
If length = 0 Then Return 0 '' say
If length = 1 Then Return array(LBound(array))
Dim min As Integer = LBound(array)
For i As Integer = LBound(array) + 1 To UBound(array)
If array(i) < min Then min = array(i)
Next
Return min
End Function
Sub countingSort(array() As Integer, min As Integer, max As Integer)
Dim count(0 To max - min) As Integer '' all zero by default
Dim As Integer number, z
For i As Integer = LBound(array) To UBound(array)
number = array(i)
count(number - min) += 1
Next
z = LBound(array)
For i As Integer = min To max
While count(i - min) > 0
array(z) = i
z += 1
count(i - min) -= 1
Wend
Next
End Sub
Sub printArray(array() As Integer)
For i As Integer = LBound(array) To UBound(array)
Print Using "####"; array(i);
Next
Print
End Sub
Dim array(1 To 10) As Integer = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1} '' using BBC BASIC example array
Print "Unsorted : ";
printArray(array())
Dim max As Integer = findMax(array())
Dim min As Integer = findMin(array())
countingSort array(), min, max
Print "Sorted : ";
printArray(array())
Print
Print "Press any key to quit"
Sleep</lang>
{{out}}
<pre>
Unsorted : 4 65 2 -31 0 99 2 83 782 1
Sorted : -31 0 1 2 2 4 65 83 99 782
</pre>
=={{header|Go}}==
This version follows the task pseudocode above, with one more optimization.
|