8. Implementation
Swift襯 螻 螻襴讀 危エ覲願給.
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
}
print("inputArray : (array)")
print("countArray : (countArray)")
// 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(accumulated) : (countArray))
....
9. Implementation
....
// Step 3
// Place the element in the final array as per the number of elements before
it
print("inputArray : (array)")
var sortedArray = [Int](repeating: 0, count: array.count)
for element in array {
countArray[element] -= 1
sortedArray[countArray[element]] = element
print("豢 覦一伎 (countArray[element]) 覯讌 碁煙れ 覦一 (element) 螳
l")
//print("countArray[(element)] : (countArray[element])")
}
print("sortedArray : (sortedArray)")
return sortedArray
}