Skip to content

Commit f355bad

Browse files
committed
Added playground demonstrating radixSort.
1 parent d44abb8 commit f355bad

File tree

3 files changed

+66
-0
lines changed

3 files changed

+66
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
//: Playground - noun: a place where people can play
2+
3+
import Cocoa
4+
5+
// Test Radix Sort with small array of ten values
6+
var array: [Int] = [19, 4242, 2, 9, 912, 101, 55, 67, 89, 32]
7+
radixSort(&array)
8+
9+
// Test Radix Sort with large array of 1000 random values
10+
var bigArray = [Int](repeating: 0, count: 1000)
11+
var i = 0
12+
while i < 1000 {
13+
bigArray[i] = Int(arc4random_uniform(1000) + 1)
14+
i += 1
15+
}
16+
radixSort(&bigArray)
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/*
2+
3+
Sorting Algorithm that sorts an input array of integers digit by digit.
4+
5+
*/
6+
import Foundation
7+
8+
// NOTE: This implementation does not handle negative numbers
9+
public func radixSort(_ array: inout [Int] ) {
10+
let radix = 10 //Here we define our radix to be 10
11+
var done = false
12+
var index: Int
13+
var digit = 1 //Which digit are we on?
14+
15+
16+
while !done { //While our sorting is not completed
17+
done = true //Assume it is done for now
18+
19+
var buckets: [[Int]] = [] //Our sorting subroutine is bucket sort, so let us predefine our buckets
20+
21+
for _ in 1...radix {
22+
buckets.append([])
23+
}
24+
25+
26+
for number in array {
27+
index = number / digit //Which bucket will we access?
28+
buckets[index % radix].append(number)
29+
if done && index > 0 { //If we arent done, continue to finish, otherwise we are done
30+
done = false
31+
}
32+
}
33+
34+
var i = 0
35+
36+
for j in 0..<radix {
37+
let bucket = buckets[j]
38+
for number in bucket {
39+
array[i] = number
40+
i += 1
41+
}
42+
}
43+
44+
digit *= radix //Move to the next digit
45+
}
46+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='macos'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>

0 commit comments

Comments
 (0)