forked from kodecocodes/swift-algorithm-club
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CountingSort.swift
38 lines (32 loc) · 950 Bytes
/
CountingSort.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//
// Sort.swift
// test
//
// Created by Kauserali on 11/04/16.
// Copyright © 2016 Ali Hafizji. All rights reserved.
//
func countingSort(_ array: [Int])-> [Int] {
guard array.count > 0 else {return []}
// Step 1
// Create an array to store the count of each element
let maxElement = array.max() ?? 0
var countArray = [Int](repeating: 0, count: Int(maxElement + 1))
for element in array {
countArray[element] += 1
}
// Step 2
// Set each value to be the sum of the previous two values
for index in 1 ..< countArray.count {
let sum = countArray[index] + countArray[index - 1]
countArray[index] = sum
}
print(countArray)
// Step 3
// Place the element in the final array as per the number of elements before it
var sortedArray = [Int](repeating: 0, count: array.count)
for element in array {
countArray[element] -= 1
sortedArray[countArray[element]] = element
}
return sortedArray
}