Skip to content

Commit d82954f

Browse files
committed
added convenience method
1 parent 185571d commit d82954f

File tree

3 files changed

+47
-10
lines changed

3 files changed

+47
-10
lines changed

Insertion Sort/InsertionSort.playground/Contents.swift

+25-10
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,34 @@ print("Hello, Swift 4!")
66
#endif
77

88
func insertionSort<T>(_ array: [T], _ isOrderedBefore: (T, T) -> Bool) -> [T] {
9-
var a = array
10-
for x in 1..<a.count {
11-
var y = x
12-
let temp = a[y]
13-
while y > 0 && isOrderedBefore(temp, a[y - 1]) {
14-
a[y] = a[y - 1]
15-
y -= 1
9+
var a = array
10+
for x in 1..<a.count {
11+
var y = x
12+
let temp = a[y]
13+
while y > 0 && isOrderedBefore(temp, a[y - 1]) {
14+
a[y] = a[y - 1]
15+
y -= 1
16+
}
17+
a[y] = temp
1618
}
17-
a[y] = temp
18-
}
19-
return a
19+
return a
20+
}
21+
22+
func insertionSort<T: Comparable>(_ array: [T]) -> [T] {
23+
var a = array
24+
for x in 1..<a.count {
25+
var y = x
26+
let temp = a[y]
27+
while y > 0 && temp < a[y - 1] {
28+
a[y] = a[y - 1]
29+
y -= 1
30+
}
31+
a[y] = temp
32+
}
33+
return a
2034
}
2135

2236
let list = [ 10, -1, 3, 9, 2, 27, 8, 5, 1, 3, 0, 26 ]
37+
insertionSort(list)
2338
insertionSort(list, <)
2439
insertionSort(list, >)
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>

Insertion Sort/InsertionSort.swift

+14
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,17 @@ func insertionSort<T>(_ array: [T], _ isOrderedBefore: (T, T) -> Bool) -> [T] {
1313
}
1414
return a
1515
}
16+
17+
func insertionSort<T: Comparable>(_ array: [T]) -> [T] {
18+
var a = array
19+
for x in 1..<a.count {
20+
var y = x
21+
let temp = a[y]
22+
while y > 0 && temp < a[y - 1] {
23+
a[y] = a[y - 1]
24+
y -= 1
25+
}
26+
a[y] = temp
27+
}
28+
return a
29+
}

0 commit comments

Comments
 (0)