-
Notifications
You must be signed in to change notification settings - Fork 0
/
counting_sort.swift
51 lines (40 loc) · 1.19 KB
/
counting_sort.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
39
40
41
42
43
44
45
46
47
48
49
50
51
let array = [4,2,2,8,3,3,1,11,6,3,56,6]
func getMaxValue(from array: [Int]) -> Int {
var maxValue = 0
for value in array {
if value > maxValue {
maxValue = value
}
}
return maxValue
}
func createCountArray(with array: [Int], and maxValue: Int) -> [Int] {
var countArray = Array(repeating: 0, count: maxValue + 1)
for element in array {
countArray[element] += 1
}
return countArray
}
func createCumulativeSumArray(from countArray: inout [Int]) -> [Int] {
for i in 1..<countArray.count {
countArray[i] += countArray[i - 1]
}
return countArray
}
func generateOutputArray(with array: [Int], and cumulativeArray: inout [Int]) -> [Int] {
var outputArray = Array(repeating: 0, count: array.count)
for element in array {
let index = cumulativeArray[element] - 1
outputArray[index] = element
cumulativeArray[element] -= 1
}
return outputArray
}
func countingSort(array: [Int]) -> [Int] {
let maxValue = getMaxValue(from: array)
var countArray = createCountArray(with: array, and: maxValue)
var cumulativeArray = createCumulativeSumArray(from: &countArray)
let output = generateOutputArray(with: array, and: &cumulativeArray)
return output
}
print(countingSort(array: array))