Add the section of radix sort. (#441)

This commit is contained in:
Yudong Jin
2023-03-26 22:02:37 +08:00
committed by GitHub
parent 4830dffd26
commit 34a1bca627
16 changed files with 405 additions and 142 deletions

View File

@@ -11,50 +11,49 @@ func digit(num: Int, exp: Int) -> Int {
}
/* nums k */
func countingSort(nums: inout [Int], exp: Int) {
// 0~9 10
var bucket = Array(repeating: 0, count: 10)
func countingSortDigit(nums: inout [Int], exp: Int) {
// 0~9 10
var counter = Array(repeating: 0, count: 10)
let n = nums.count
// 0~9
// 0~9
for i in nums.indices {
let d = digit(num: nums[i], exp: exp) // nums[i] k d
bucket[d] += 1 // d
counter[d] += 1 // d
}
//
for i in 1 ..< 10 {
bucket[i] += bucket[i - 1]
counter[i] += counter[i - 1]
}
// tmp
var tmp = Array(repeating: 0, count: n)
// res
var res = Array(repeating: 0, count: n)
for i in stride(from: n - 1, through: 0, by: -1) {
let d = digit(num: nums[i], exp: exp)
let j = bucket[d] - 1 // d j
tmp[j] = nums[i] // j
bucket[d] -= 1 // d 1
let j = counter[d] - 1 // d j
res[j] = nums[i] // j
counter[d] -= 1 // d 1
}
// tmp nums
// 使 nums
for i in nums.indices {
nums[i] = tmp[i]
nums[i] = res[i]
}
}
/* */
func radixSort(nums: inout [Int]) {
//
var ma = Int.min
var m = Int.min
for num in nums {
if num > ma {
ma = num
if num > m {
m = num
}
}
//
for exp in sequence(first: 1, next: { ma >= ($0 * 10) ? $0 * 10 : nil }) {
// k
for exp in sequence(first: 1, next: { m >= ($0 * 10) ? $0 * 10 : nil }) {
// k
// k = 1 -> exp = 1
// k = 2 -> exp = 10
// k = 3 -> exp = 100
// exp = 10^(k-1)
countingSort(nums: &nums, exp: exp)
countingSortDigit(nums: &nums, exp: exp)
}
}
@@ -62,8 +61,9 @@ func radixSort(nums: inout [Int]) {
enum RadixSort {
/* Driver Code */
static func main() {
/* */
var nums = [23, 12, 3, 4, 788, 192]
//
var nums = [10546151, 35663510, 42865989, 34862445, 81883077,
88906420, 72429244, 30524779, 82060337, 63832996]
radixSort(nums: &nums)
print("基数排序完成后 nums = \(nums)")
}