Skip to content

Commit 7cee0b6

Browse files
authored
Merge pull request #384 from AdrianBinDC/patch-2
Update CountingSort.swift to Swift 3.0 syntax
2 parents b9b3411 + ba39752 commit 7cee0b6

File tree

1 file changed

+34
-32
lines changed

1 file changed

+34
-32
lines changed

Counting Sort/CountingSort.swift

+34-32
Original file line numberDiff line numberDiff line change
@@ -6,39 +6,41 @@
66
// Copyright © 2016 Ali Hafizji. All rights reserved.
77
//
88

9-
enum CountingSortError: ErrorType {
10-
case arrayEmpty
9+
import Foundation
10+
11+
enum CountingSortError: Error {
12+
case arrayEmpty
1113
}
1214

1315
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
4446
}

0 commit comments

Comments
 (0)