Sorting is one of the most important ideas in computer science, and Radix Sort is a unique method that solves the problem by looking at numbers digit by digit. Instead of comparing values directly, it groups digits and processes them from the smallest place value to the largest. This gives Radix Sort a smooth rhythm and makes it very beginner-friendly once you understand the flow. Many people find it easier to learn than some of the heavier comparison-based sorting techniques.
with hands-on learning.
get the skills and confidence to land your next move.
Radix Sort matters because it offers a predictable time pattern, especially when the size of the digits stays small. In real software, it can appear in tasks such as organizing ID numbers, sorting fixed-length strings, arranging financial data, or preparing structured values before deeper analysis. Understanding Radix Sort in Swift helps you build confidence in algorithmic thinking, and it shows how data can be handled in simple steps without relying on comparisons.
Program 1: Basic Radix Sort Using Loops
This first program shows a simple loop-based version of Radix Sort, working from the least significant digit upward. It uses a familiar structure so beginners can feel comfortable.
import Foundation
func radixSort(_ array: [Int]) -> [Int] {
var numbers = array
var place = 1
let maxNumber = numbers.max() ?? 0
while maxNumber / place > 0 {
var buckets = Array(repeating: [Int](), count: 10)
for num in numbers {
let digit = (num / place) % 10
buckets[digit].append(num)
}
numbers = buckets.flatMap { $0 }
place *= 10
}
return numbers
}
let data = [170, 45, 75, 90, 802, 24, 2, 66]
print("Sorted:", radixSort(data))This version uses simple loops to pull apart digits, store them in buckets, and rebuild the list one place value at a time. It is useful because it avoids recursion and gives a clear view of how Radix Sort flows through each digit. Beginners often find it easier to understand because everything is visible and predictable in the loop behavior.
Program 2: Radix Sort with a Helper Function
This program breaks the logic into smaller pieces by adding a helper method. It makes the code feel more organized and easier to maintain.
import Foundation
func countingSortByDigit(_ array: [Int], place: Int) -> [Int] {
var output = Array(repeating: 0, count: array.count)
var count = Array(repeating: 0, count: 10)
for num in array {
let digit = (num / place) % 10
count[digit] += 1
}
for i in 1..<10 {
count[i] += count[i - 1]
}
for num in array.reversed() {
let digit = (num / place) % 10
count[digit] -= 1
output[count[digit]] = num
}
return output
}
func radixSortHelper(_ array: [Int]) -> [Int] {
var numbers = array
let maxNumber = numbers.max() ?? 0
var place = 1
while maxNumber / place > 0 {
numbers = countingSortByDigit(numbers, place: place)
place *= 10
}
return numbers
}
let data = [91, 802, 24, 45, 66, 170, 75, 2]
print("Sorted:", radixSortHelper(data))This approach is helpful because splitting the work into smaller functions teaches beginners how to structure algorithms more cleanly. The helper performs digit sorting, and the main function simply manages the cycle. This style is easier to reuse in larger apps where you want cleaner code.
Program 3: Radix Sort Using Recursion
Here we take a more creative turn and use recursion. Instead of looping through place values, the recursion handles each digit level automatically.
import Foundation
func radixSortRecursive(_ array: [Int], place: Int = 1) -> [Int] {
let maxNumber = array.max() ?? 0
if maxNumber / place == 0 {
return array
}
var buckets = Array(repeating: [Int](), count: 10)
for num in array {
let digit = (num / place) % 10
buckets[digit].append(num)
}
let merged = buckets.flatMap { $0 }
return radixSortRecursive(merged, place: place * 10)
}
let data = [99, 12, 345, 10, 501, 2, 28]
print("Sorted:", radixSortRecursive(data))The recursive version feels elegant because the function naturally calls itself until the largest digit is processed. This style is useful for learners who want to understand recursion in a real algorithm. It teaches how a problem can shrink step by step until no more digits remain.
Program 4: Radix Sort for Negative Numbers
Radix Sort usually works with positive values, but with a small adjustment we can include negative integers as well.
import Foundation
// Classic Radix Sort for positive integers
func radixSort(_ array: [Int]) -> [Int] {
var numbers = array
var place = 1
let maxNumber = numbers.max() ?? 0
while maxNumber / place > 0 {
var buckets = Array(repeating: [Int](), count: 10)
for num in numbers {
let digit = (num / place) % 10
buckets[digit].append(num)
}
numbers = buckets.flatMap { $0 }
place *= 10
}
return numbers
}
// Radix Sort that supports negative numbers
func radixSortWithNegatives(_ array: [Int]) -> [Int] {
// Separate positives and negatives
let positives = array.filter { $0 >= 0 }
let negatives = array.filter { $0 < 0 }.map { -$0 }
// Sort each part
let sortedPos = radixSort(positives)
let sortedNeg = radixSort(negatives).reversed().map { -$0 }
// Combine negatives and positives
return sortedNeg + sortedPos
}
let data = [170, -45, 75, -90, 802, 24, -2, 66]
let sorted = radixSortWithNegatives(data)
print("Sorted:", sorted)This method works by separating the negative and positive values and sorting each group independently. The negative numbers are sorted using their absolute values and then flipped back. This is useful because many real-world datasets include both positive and negative values, and beginners benefit from learning how to adapt algorithms.
Program 5: Radix Sort for Strings (Character Codes)
This program shows how Radix Sort can also work with words when you sort them using character codes.
import Foundation
func radixSortStrings(_ array: [String]) -> [String] {
let maxLength = array.map { $0.count }.max() ?? 0
var strings = array.map { $0.padding(toLength: maxLength, withPad: " ", startingAt: 0) }
for place in (0..<maxLength).reversed() {
var buckets = Array(repeating: [String](), count: 256)
for word in strings {
let index = Int(word[word.index(word.startIndex, offsetBy: place)].asciiValue ?? 0)
buckets[index].append(word)
}
strings = buckets.flatMap { $0 }
}
return strings.map { $0.trimmingCharacters(in: .whitespaces) }
}
let data = ["lion", "cat", "zebra", "ant", "dog"]
print("Sorted:", radixSortStrings(data))This version extends Radix Sort beyond numbers by working with ASCII values of characters. It is useful because many real tasks involve sorting names, words, or identifiers. Beginners learn that Radix Sort is flexible and can handle many kinds of data as long as there is a clear ordering.
Frequently Asked Questions (FAQ)
This short FAQ section offers simple explanations to help beginners understand common questions about Radix Sort.
Q1: Why is Radix Sort different from other sorting algorithms?
Radix Sort does not compare values directly. It works digit by digit, which gives it a unique flow and predictable timing.
Q2: Does Radix Sort always need buckets?
Yes, buckets are essential because they hold groups of digits while the sort passes through each place value.
Q3: Can Radix Sort handle floating-point numbers?
Not directly. They need to be converted to a form that works with integer digits, such as scaled integers.
Q4: Is Radix Sort faster than Quick Sort?
It depends on the data. Radix Sort shines when digit sizes are limited, while Quick Sort works well on general data.
Q5: Can I use Radix Sort in real Swift apps?
You can, especially when sorting large sets of fixed-format data like IDs, strings, codes, or structured numbers.
Conclusion
Radix Sort is a friendly algorithm once you understand that it moves step by step through the digits instead of comparing entire numbers at once. It gives beginners a strong foundation because its logic is easy to follow, and its structure stays consistent across different types of data. By trying the different Swift programs above, you can explore loops, recursion, buckets, and even sorting strings. The best way to grow is to practice, experiment with new data, and see how Radix Sort behaves in your own projects.




