forked from wangzheng0822/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
96c7e13
commit 52f8404
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
// | ||
// CountingSort.swift | ||
// algo | ||
// | ||
// Created by Wenru Dong on 2018/10/18. | ||
// Copyright © 2018年 Wenru Dong. All rights reserved. | ||
// | ||
|
||
import Foundation | ||
|
||
// 假设数组中储存的都是非负整数 | ||
public func countingSort(_ a: inout [Int]) { | ||
if a.count <= 1 { return } | ||
|
||
var counts = Array(repeating: 0, count: a.max()! + 1) | ||
for num in a { | ||
counts[num] += 1 | ||
} | ||
for i in 1..<counts.count { | ||
counts[i] = counts[i-1] + counts[i] | ||
} | ||
|
||
var aSorted = Array(repeating: 0, count: a.count) | ||
for num in a.reversed() { | ||
let index = counts[num] - 1 | ||
aSorted[index] = num | ||
counts[num] -= 1 | ||
} | ||
|
||
for (i, num) in aSorted.enumerated() { | ||
a[i] = num | ||
} | ||
} |