|
6 | 6 | // Copyright © 2016 Ali Hafizji. All rights reserved.
|
7 | 7 | //
|
8 | 8 |
|
9 |
| -enum CountingSortError: ErrorType { |
10 |
| - case arrayEmpty |
| 9 | +import Foundation |
| 10 | + |
| 11 | +enum CountingSortError: Error { |
| 12 | + case arrayEmpty |
11 | 13 | }
|
12 | 14 |
|
13 | 15 | func countingSort(array: [Int]) throws -> [Int] {
|
14 |
| - guard array.count > 0 else { |
15 |
| - throw CountingSortError.arrayEmpty |
16 |
| - } |
17 |
| - |
18 |
| - // Step 1 |
19 |
| - // Create an array to store the count of each element |
20 |
| - let maxElement = array.maxElement() ?? 0 |
21 |
| - |
22 |
| - var countArray = [Int](count: Int(maxElement + 1), repeatedValue: 0) |
23 |
| - for element in array { |
24 |
| - countArray[element] += 1 |
25 |
| - } |
26 |
| - |
27 |
| - // Step 2 |
28 |
| - // Set each value to be the sum of the previous two values |
29 |
| - for index in 1 ..< countArray.count { |
30 |
| - let sum = countArray[index] + countArray[index - 1] |
31 |
| - countArray[index] = sum |
32 |
| - } |
33 |
| - |
34 |
| - print(countArray) |
35 |
| - |
36 |
| - // Step 3 |
37 |
| - // Place the element in the final array as per the number of elements before it |
38 |
| - var sortedArray = [Int](count: array.count, repeatedValue: 0) |
39 |
| - for element in array { |
40 |
| - countArray[element] -= 1 |
41 |
| - sortedArray[countArray[element]] = element |
42 |
| - } |
43 |
| - return sortedArray |
| 16 | + guard array.count > 0 else { |
| 17 | + throw CountingSortError.arrayEmpty |
| 18 | + } |
| 19 | + |
| 20 | + // Step 1 |
| 21 | + // Create an array to store the count of each element |
| 22 | + let maxElement = array.max() ?? 0 |
| 23 | + |
| 24 | + var countArray = [Int](repeating: 0, count: Int(maxElement + 1)) |
| 25 | + for element in array { |
| 26 | + countArray[element] += 1 |
| 27 | + } |
| 28 | + |
| 29 | + // Step 2 |
| 30 | + // Set each value to be the sum of the previous two values |
| 31 | + for index in 1 ..< countArray.count { |
| 32 | + let sum = countArray[index] + countArray[index - 1] |
| 33 | + countArray[index] = sum |
| 34 | + } |
| 35 | + |
| 36 | + print(countArray) |
| 37 | + |
| 38 | + // Step 3 |
| 39 | + // Place the element in the final array as per the number of elements before it |
| 40 | + var sortedArray = [Int](repeating: 0, count: array.count) |
| 41 | + for element in array { |
| 42 | + countArray[element] -= 1 |
| 43 | + sortedArray[countArray[element]] = element |
| 44 | + } |
| 45 | + return sortedArray |
44 | 46 | }
|
0 commit comments