Skip to content

Commit a3959be

Browse files
authored
Merge pull request #1 from jVirus/sort/shell-core_implementation
Implemented Shell sort as Array extension
2 parents 0ab9ce5 + a9757b7 commit a3959be

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
//: [Previous](@previous)
2+
3+
import Foundation
4+
5+
// Shell sort is an improved version of insertion sort. The original list is broken into smaller sublists and then individually sorted using insertion sort.
6+
7+
extension Array where Element: Comparable {
8+
9+
public mutating func shellSorted(order sign: (Element, Element) -> Bool) {
10+
var subcount = self.count / 2
11+
12+
while subcount > 0 {
13+
for i in 0..<self.count {
14+
let temp = self[i]
15+
var j = i
16+
17+
while j >= subcount && sign(self[j - subcount], temp) {
18+
self[j] = self[j - subcount]
19+
j -= subcount
20+
}
21+
self[j] = temp
22+
}
23+
subcount /= 2
24+
}
25+
26+
}
27+
}
28+
29+
//: Usage
30+
31+
var data = [4, 1, 5, 6, 1, 2, 9, 8, 5, 4, 2, 7, 6]
32+
data.shellSorted(order: >)
33+
34+
//: [Next](@next)

Sort.playground/contents.xcplayground

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,6 @@
66
<page name='Quick-Hoare-Scheme'/>
77
<page name='Quick-Lomuto-Scheme'/>
88
<page name='Bubble'/>
9+
<page name='Shell'/>
910
</pages>
1011
</playground>

0 commit comments

Comments
 (0)