There was an error while loading. Please reload this page.
2 parents 5d400b7 + 52f8404 commit a21e8c5Copy full SHA for a21e8c5
swift/14_sorts/CountingSort.swift
@@ -0,0 +1,33 @@
1
+//
2
+// CountingSort.swift
3
+// algo
4
5
+// Created by Wenru Dong on 2018/10/18.
6
+// Copyright © 2018年 Wenru Dong. All rights reserved.
7
8
+
9
+import Foundation
10
11
+// 假设数组中储存的都是非负整数
12
+public func countingSort(_ a: inout [Int]) {
13
+ if a.count <= 1 { return }
14
15
+ var counts = Array(repeating: 0, count: a.max()! + 1)
16
+ for num in a {
17
+ counts[num] += 1
18
+ }
19
+ for i in 1..<counts.count {
20
+ counts[i] = counts[i-1] + counts[i]
21
22
23
+ var aSorted = Array(repeating: 0, count: a.count)
24
+ for num in a.reversed() {
25
+ let index = counts[num] - 1
26
+ aSorted[index] = num
27
+ counts[num] -= 1
28
29
30
+ for (i, num) in aSorted.enumerated() {
31
+ a[i] = num
32
33
+}
0 commit comments