Skip to content

Commit a21e8c5

Browse files
Merge pull request wangzheng0822#88 from jerryderry/counting-sort-swift
Counting sort in swift
2 parents 5d400b7 + 52f8404 commit a21e8c5

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

swift/14_sorts/CountingSort.swift

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)