Skip to content

Commit 4c796cc

Browse files
committed
[Swift 4] Update Shell Sort
1 parent 1eb05ba commit 4c796cc

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

Diff for: Shell Sort/Shell Sort.playground/Contents.swift

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
//: Playground - noun: a place where people can play
2+
3+
import UIKit
4+
5+
// last checked with Xcode 9.0b4
6+
#if swift(>=4.0)
7+
print("Hello, Swift 4!")
8+
#endif
9+
10+
public func insertionSort(_ list: inout [Int], start: Int, gap: Int) {
11+
for i in stride(from: (start + gap), to: list.count, by: gap) {
12+
let currentValue = list[i]
13+
var pos = i
14+
while pos >= gap && list[pos - gap] > currentValue {
15+
list[pos] = list[pos - gap]
16+
pos -= gap
17+
}
18+
list[pos] = currentValue
19+
}
20+
}
21+
22+
public func shellSort(_ list: inout [Int]) {
23+
var sublistCount = list.count / 2
24+
while sublistCount > 0 {
25+
for pos in 0..<sublistCount {
26+
insertionSort(&list, start: pos, gap: sublistCount)
27+
}
28+
sublistCount = sublistCount / 2
29+
}
30+
}
31+
32+
var arr = [64, 20, 50, 33, 72, 10, 23, -1, 4, 5]
33+
34+
shellSort(&arr)
+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>

0 commit comments

Comments
 (0)