From 128f8b3cbcbe9f21003e8f0827cd18e2eea589ad Mon Sep 17 00:00:00 2001 From: Ayush Jain <42704976+Ayushjain9501@users.noreply.github.com> Date: Mon, 6 May 2019 17:18:11 +0530 Subject: [PATCH] Added Swift Implementation of Counting Sort (#35719) --- .../sorting-algorithms/counting-sort/index.md | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/guide/english/algorithms/sorting-algorithms/counting-sort/index.md b/guide/english/algorithms/sorting-algorithms/counting-sort/index.md index 76d47cb169..9703a4e0ee 100644 --- a/guide/english/algorithms/sorting-algorithms/counting-sort/index.md +++ b/guide/english/algorithms/sorting-algorithms/counting-sort/index.md @@ -80,3 +80,30 @@ void countSort(int upperBound, int lowerBound, std::vector numbersToSort) / std::cout << counts << std::endl; } ``` + +### Swift Implementation +```swift +func countingSort(_ array: [Int]) { + // 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 + } + var z = 0 + var sortedArray = [Int](repeating: 0, count: array.count) + + for index in 1 ..< countArray.count { + //print index element required number of times + while countArray[index] > 0 { + sortedArray[z] = index + z += 1 + countArray[index] -= 1 + } + } + + print(sortedArray) +} + + ```