Skip to content

Commit c454df2

Browse files
authored
Merge pull request #625 from jakecast/patch-1
update to radix sort
2 parents 0464cbb + 50ff5a2 commit c454df2

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)