Implementing Radix Sort Fast AF

Swift Fast AF
2 min readDec 20, 2022

--

Radix Sort is an efficient sorting algorithm that works by sorting elements based on their digits. It is particularly useful for sorting large arrays of integers or strings. In this tutorial, we will learn how to implement Radix Sort in Swift.

Before we begin, let’s understand the basic concepts of Radix Sort. It works by sorting elements based on their digits from least significant to most significant. For example, if we have an array of integers, we would start by sorting them based on their units digit, then their tens digit, and so on.

To implement Radix Sort in Swift, we first need to define a function that takes in an array of integers as input. We will call this function radixSort(). Inside the function, we will create a variable called maxDigits that will store the maximum number of digits among all the elements in the array.

Next, we will create a loop that iterates from 0 to maxDigits. Inside the loop, we will create a new array called buckets that will store the elements based on their digits. We will then iterate over the elements in the array and place them in the appropriate bucket based on their digits.

Finally, we will concatenate all the elements in the buckets and return the sorted array.

Here is the code for the radixSort() function:

func radixSort(array: [Int]) -> [Int] {
var maxDigits = 0

for number in array {
let digits = String(number).count
if digits > maxDigits {
maxDigits = digits
}
}

for i in 0..<maxDigits {
var buckets: [[Int]] = Array(repeating: [], count: 10)

for number in array {
let digit = number % Int(pow(10, i+1)) / Int(pow(10, i))
buckets[digit].append(number)
}

array = buckets.flatMap { $0 }
}

return array
}

Now, let’s test the function by calling it with an array of integers:

let array = [432, 981, 234, 654, 789, 123, 345, 456, 567]
let sortedArray = radixSort(array: array)
print(sortedArray) // [123, 234, 345, 432, 456, 567, 654, 789, 981]

As you can see, the function has successfully sorted the array in ascending order.

Radix Sort is a useful algorithm for sorting large arrays of integers or strings. It is efficient and easy to implement in Swift. If you want to learn more about Radix Sort and other sorting algorithms, you can check out the following resources:

--

--