Counting Sort

Counting sort is sorting algorithm based on keys between specific range. It works by counting the number of objects having distinct key values. Then doing some arithmetic to calculate the position of each object in the output sequence.



									Public Shared Sub CountingSort(ByRef data As Integer(), min As Integer, max As Integer)
	Dim count As Integer() = New Integer(max - min) {}
	Dim z As Integer = 0

	For i As Integer = 0 To count.Length - 1
		count(i) = 0
	Next

	For i As Integer = 0 To data.Length - 1
		count(data(i) - min) += 1
	Next

	For i As Integer = min To max
		While System.Math.Max(System.Threading.Interlocked.Decrement(count(i - min)), count(i - min) + 1) > 0
			data(z) = i
			z += 1
		End While
	Next
End Sub
								


Example

									Dim data() As Integer = { -1, 25, -58964, 8547, -119, 0, 78596 }
CountingSort(data, -58964, 78596)
								


Output

									-58964
-119
-1
0
25
8547
78596