Skip to content

Commit 44711ad

Browse files
committed
addition of convenience method
1 parent 185571d commit 44711ad

File tree

3 files changed

+33
-2
lines changed

3 files changed

+33
-2
lines changed

Selection Sort/SelectionSort.playground/Contents.swift

+1
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,6 @@ print("Hello, Swift 4!")
66
#endif
77

88
let list = [ 10, -1, 3, 9, 2, 27, 8, 5, 1, 3, 0, 26 ]
9+
selectionSort(list)
910
selectionSort(list, <)
1011
selectionSort(list, >)

Selection Sort/SelectionSort.playground/Sources/SelectionSort.swift

+24-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
public func selectionSort<T: Comparable>(_ array: [T], _ isOrderedBefore: (T, T) -> Bool) -> [T] {
1+
public func selectionSort<T: Comparable>(_ array: [T]) -> [T] {
22
guard array.count > 1 else { return array }
33

44
var a = array
@@ -7,7 +7,7 @@ public func selectionSort<T: Comparable>(_ array: [T], _ isOrderedBefore: (T, T)
77
// Find the lowest value in the rest of the array.
88
var lowest = x
99
for y in x + 1 ..< a.count {
10-
if isOrderedBefore(a[y], a[lowest]) {
10+
if a[y] < a[lowest] {
1111
lowest = y
1212
}
1313
}
@@ -19,3 +19,25 @@ public func selectionSort<T: Comparable>(_ array: [T], _ isOrderedBefore: (T, T)
1919
}
2020
return a
2121
}
22+
23+
public func selectionSort<T>(_ array: [T], _ isLowerThan: (T, T) -> Bool) -> [T] {
24+
guard array.count > 1 else { return array }
25+
26+
var a = array
27+
for x in 0 ..< a.count - 1 {
28+
29+
// Find the lowest value in the rest of the array.
30+
var lowest = x
31+
for y in x + 1 ..< a.count {
32+
if isLowerThan(a[y], a[lowest]) {
33+
lowest = y
34+
}
35+
}
36+
37+
// Swap the lowest value with the current array index.
38+
if x != lowest {
39+
a.swapAt(x, lowest)
40+
}
41+
}
42+
return a
43+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+
<plist version="1.0">
4+
<dict>
5+
<key>IDEDidComputeMac32BitWarning</key>
6+
<true/>
7+
</dict>
8+
</plist>

0 commit comments

Comments
 (0)