Skip to content

Commit

Permalink
addition of convenience method
Browse files Browse the repository at this point in the history
  • Loading branch information
JulioBBL committed Oct 1, 2018
1 parent 185571d commit 44711ad
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
1 change: 1 addition & 0 deletions Selection Sort/SelectionSort.playground/Contents.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@ print("Hello, Swift 4!")
#endif

let list = [ 10, -1, 3, 9, 2, 27, 8, 5, 1, 3, 0, 26 ]
selectionSort(list)
selectionSort(list, <)
selectionSort(list, >)
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
public func selectionSort<T: Comparable>(_ array: [T], _ isOrderedBefore: (T, T) -> Bool) -> [T] {
public func selectionSort<T: Comparable>(_ array: [T]) -> [T] {
guard array.count > 1 else { return array }

var a = array
Expand All @@ -7,7 +7,7 @@ public func selectionSort<T: Comparable>(_ array: [T], _ isOrderedBefore: (T, T)
// Find the lowest value in the rest of the array.
var lowest = x
for y in x + 1 ..< a.count {
if isOrderedBefore(a[y], a[lowest]) {
if a[y] < a[lowest] {
lowest = y
}
}
Expand All @@ -19,3 +19,25 @@ public func selectionSort<T: Comparable>(_ array: [T], _ isOrderedBefore: (T, T)
}
return a
}

public func selectionSort<T>(_ array: [T], _ isLowerThan: (T, T) -> Bool) -> [T] {
guard array.count > 1 else { return array }

var a = array
for x in 0 ..< a.count - 1 {

// Find the lowest value in the rest of the array.
var lowest = x
for y in x + 1 ..< a.count {
if isLowerThan(a[y], a[lowest]) {
lowest = y
}
}

// Swap the lowest value with the current array index.
if x != lowest {
a.swapAt(x, lowest)
}
}
return a
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>

0 comments on commit 44711ad

Please sign in to comment.