Skip to content

Instantly share code, notes, and snippets.

@davidinga
Created August 20, 2019 20:33
Show Gist options
  • Select an option

  • Save davidinga/56f452e97187354d615223bb72ff1c8d to your computer and use it in GitHub Desktop.

Select an option

Save davidinga/56f452e97187354d615223bb72ff1c8d to your computer and use it in GitHub Desktop.
Extends Array<Int> to include Radix Sort. Uses Counting Sort as a subroutine. This implementation is for nonnegative, base 10 integers.
extension Array where Element == Int {
mutating func radixSort() {
let radix = 10
var digit = 1
var done = false
var unsortedArray = self
while !done {
done = true
/// Counting Sort: Step 1
/// - Tally each number in count array.
var countArray = Array<Int>(repeating: 0, count: radix)
for number in unsortedArray {
guard number >= 0 else {
return
}
let index = number / digit
countArray[index % radix] += 1
if index > 0 && done {
done = false
}
}
/// Counting Sort: Step 2
/// - Modify count array to apply proper indices.
for i in 1..<radix {
countArray[i] += countArray[i - 1]
}
/// Counting Sort: Step 3
/// - Build sorted array from indices in count array.
var sortedArray = Array<Int>(repeating: 0, count: unsortedArray.count)
/// Iterate over elements in reverse for stable sort.
for number in unsortedArray.reversed() {
let index = (number / digit) % radix
countArray[index] -= 1
sortedArray[countArray[index]] = number
}
unsortedArray = sortedArray
digit *= radix
}
self = unsortedArray
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment