Skip to content

Commit 50ff5a2

Browse files
authored
update to radix sort
tracking the largest value in the array on the first iteration of the bucket sort allows you to do one less loop and drops the need for a `done` variable. also updated the bucket initialization to use the `(repeatingElement: count:)` initializer and switched to using an iterator for looping through the buckets instead of accessing them based on the range loop.
1 parent 0464cbb commit 50ff5a2

File tree

1 file changed

+31
-39
lines changed

1 file changed

+31
-39
lines changed

Radix Sort/radixSort.swift

Lines changed: 31 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -5,43 +5,35 @@
55
*/
66

77

8-
func radixSort(inout arr: [Int] ) {
9-
10-
11-
let radix = 10 //Here we define our radix to be 10
12-
var done = false
13-
var index: Int
14-
var digit = 1 //Which digit are we on?
15-
16-
17-
while !done { //While our sorting is not completed
18-
done = true //Assume it is done for now
19-
20-
var buckets: [[Int]] = [] //Our sorting subroutine is bucket sort, so let us predefine our buckets
21-
22-
for _ in 1...radix {
23-
buckets.append([])
24-
}
25-
26-
27-
for number in arr {
28-
index = number / digit //Which bucket will we access?
29-
buckets[index % radix].append(number)
30-
if done && index > 0 { //If we arent done, continue to finish, otherwise we are done
31-
done = false
32-
}
33-
}
34-
35-
var i = 0
36-
37-
for j in 0..<radix {
38-
let bucket = buckets[j]
39-
for number in bucket {
40-
arr[i] = number
41-
i += 1
42-
}
43-
}
44-
45-
digit *= radix //Move to the next digit
46-
}
8+
func radixSort(arr: inout [Int]) {
9+
let radix = 10
10+
11+
var digit: Int = 1
12+
var largest: Int = 0
13+
14+
var buckets: [[Int]]
15+
var index: Int
16+
var pos: Int
17+
18+
repeat {
19+
pos = 0
20+
buckets = Array(repeatElement([], count: 10))
21+
22+
for num in arr {
23+
index = num / digit
24+
buckets[index % radix].append(num)
25+
26+
if digit == 1 {
27+
largest = max(largest, num)
28+
}
29+
}
30+
for bin in buckets {
31+
for num in bin {
32+
arr[pos] = num
33+
pos = pos + 1
34+
}
35+
}
36+
37+
digit = digit * radix
38+
} while digit < largest
4739
}

0 commit comments

Comments
 (0)