Skip to content

Commit

Permalink
countingSort in swift
Browse files Browse the repository at this point in the history
  • Loading branch information
jerryderry committed Oct 18, 2018
1 parent 96c7e13 commit 52f8404
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions swift/14_sorts/CountingSort.swift
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
}
}

0 comments on commit 52f8404

Please sign in to comment.