Skip to content

Commit 9e9c84e

Browse files
authored
Merge pull request kodecocodes#745 from JulioBBL/select-sort
Select sort improvements
2 parents 9bdce27 + 7578327 commit 9e9c84e

File tree

3 files changed

+41
-18
lines changed

3 files changed

+41
-18
lines changed

Selection Sort/SelectionSort.playground/Contents.swift

Lines changed: 1 addition & 0 deletions
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, >)
Lines changed: 32 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,35 @@
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-
}
1+
/// Performs the Selection sort algorithm on a array
2+
///
3+
/// - Parameter array: array of elements that conform to the Comparable protocol
4+
/// - Returns: an array in ascending order
5+
public func selectionSort<T: Comparable>(_ array: [T]) -> [T] {
6+
return insertionSort(array, <)
7+
}
148

15-
// Swap the lowest value with the current array index.
16-
if x != lowest {
17-
a.swapAt(x, lowest)
9+
/// Performs the Selection sort algorithm on a array using the provided comparisson method
10+
///
11+
/// - Parameters:
12+
/// - array: array of elements that conform to the Comparable protocol
13+
/// - isLowerThan: returns true if the two provided elements are in the correct order
14+
/// - Returns: a sorted array
15+
public func selectionSort<T>(_ array: [T], _ isLowerThan: (T, T) -> Bool) -> [T] {
16+
guard array.count > 1 else { return array }
17+
18+
var a = array
19+
for x in 0 ..< a.count - 1 {
20+
21+
// Find the lowest value in the rest of the array.
22+
var lowest = x
23+
for y in x + 1 ..< a.count {
24+
if isLowerThan(a[y], a[lowest]) {
25+
lowest = y
26+
}
27+
}
28+
29+
// Swap the lowest value with the current array index.
30+
if x != lowest {
31+
a.swapAt(x, lowest)
32+
}
1833
}
19-
}
20-
return a
34+
return a
2135
}
Lines changed: 8 additions & 0 deletions
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)