Implementing Counting Sort Fast AF

Swift Fast AF
2 min readDec 21, 2022

--

Counting sort is an efficient sorting algorithm that works by counting the number of occurrences of each element in an array and then constructing a new sorted array based on those counts. It is particularly useful for sorting arrays with a small range of values, as it has a time complexity of O(n+k) where n is the size of the array and k is the range of values.

To implement counting sort in Swift, we first need to create a function that takes in an array and the range of values as arguments. We will also need a separate array to store the counts of each element in the original array.

Here is the code for the counting sort function:

func countingSort(array: [Int], range: Int) -> [Int] {
// Create an array to store the counts of each element
var countArray = [Int](repeating: 0, count: range+1)
// Count the occurrences of each element
for element in array {
countArray[element] += 1
}
// Create a new sorted array based on the counts
var sortedArray = [Int]()
for i in 0...range {
for _ in 0..<countArray[i] {
sortedArray.append(i)
}
}
return sortedArray
}

Now let’s test our counting sort function by creating an unsorted array and calling the function on it:

let unsortedArray = [3, 5, 1, 4, 2]
let sortedArray = countingSort(array: unsortedArray, range: 5)
print(sortedArray) // [1, 2, 3, 4, 5]

As we can see, the function correctly sorts the array in ascending order.

One important thing to note is that counting sort is not a comparison-based sorting algorithm like quicksort or merge sort. This means that it cannot be used to sort arrays with a large range of values, as the time complexity would be too high. However, it is a useful algorithm to have in your toolkit for situations where the range of values is known and relatively small.

For more information on counting sort and other sorting algorithms, you can check out the following resources:

--

--