Skip to content

Commit 207d7f9

Browse files
committed
[Swift 4] Update Selection Sort
1 parent 5ea9de2 commit 207d7f9

File tree

5 files changed

+44
-41
lines changed

5 files changed

+44
-41
lines changed

Selection Sort/SelectionSort.playground/Contents.swift

+4-16
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,9 @@
11
//: Playground - noun: a place where people can play
22

3-
func selectionSort<T>(_ array: [T], _ isOrderedBefore: (T, T) -> Bool) -> [T] {
4-
guard array.count > 1 else { return array }
5-
var a = array
6-
for x in 0 ..< a.count - 1 {
7-
var lowest = x
8-
for y in x + 1 ..< a.count {
9-
if isOrderedBefore(a[y], a[lowest]) {
10-
lowest = y
11-
}
12-
}
13-
if x != lowest {
14-
swap(&a[x], &a[lowest])
15-
}
16-
}
17-
return a
18-
}
3+
// last checked with Xcode 9.0b4
4+
#if swift(>=4.0)
5+
print("Hello, Swift 4!")
6+
#endif
197

208
let list = [ 10, -1, 3, 9, 2, 27, 8, 5, 1, 3, 0, 26 ]
219
selectionSort(list, <)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
public func selectionSort<T: Comparable>(_ array: [T], _ isOrderedBefore: (T, T) -> Bool) -> [T] {
2+
guard array.count > 1 else { return array }
3+
4+
var a = array
5+
for x in 0 ..< a.count - 1 {
6+
7+
// Find the lowest value in the rest of the array.
8+
var lowest = x
9+
for y in x + 1 ..< a.count {
10+
if isOrderedBefore(a[y], a[lowest]) {
11+
lowest = y
12+
}
13+
}
14+
15+
// Swap the lowest value with the current array index.
16+
if x != lowest {
17+
a.swapAt(x, lowest)
18+
}
19+
}
20+
return a
21+
}

Selection Sort/SelectionSort.playground/timeline.xctimeline

-6
This file was deleted.

Selection Sort/SelectionSort.swift

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

4-
var a = array
5-
for x in 0 ..< a.count - 1 {
4+
var a = array
5+
for x in 0 ..< a.count - 1 {
66

7-
// Find the lowest value in the rest of the array.
8-
var lowest = x
9-
for y in x + 1 ..< a.count {
10-
if isOrderedBefore(a[y], a[lowest]) {
11-
lowest = y
12-
}
13-
}
7+
// Find the lowest value in the rest of the array.
8+
var lowest = x
9+
for y in x + 1 ..< a.count {
10+
if isOrderedBefore(a[y], a[lowest]) {
11+
lowest = y
12+
}
13+
}
1414

15-
// Swap the lowest value with the current array index.
16-
if x != lowest {
17-
swap(&a[x], &a[lowest])
15+
// Swap the lowest value with the current array index.
16+
if x != lowest {
17+
a.swapAt(x, lowest)
18+
}
1819
}
19-
}
20-
return a
20+
return a
2121
}

swift-algorithm-club.xcworkspace/contents.xcworkspacedata

+3-3
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)