Skip to content

Commit a69e3d8

Browse files
authored
Update README.markdown
update sample code
1 parent 217cad5 commit a69e3d8

File tree

1 file changed

+22
-12
lines changed

1 file changed

+22
-12
lines changed

Shell Sort/README.markdown

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -116,21 +116,31 @@ Here is an implementation of Shell Sort in Swift:
116116
```
117117
var arr = [64, 20, 50, 33, 72, 10, 23, -1, 4, 5]
118118
119-
var n = arr.count / 2
120-
121-
repeat
122-
{
123-
for index in 0..<arr.count{
124-
125-
if (index + n) < arr.count && arr[index] > arr[index + n]{
119+
public func shellSort(_ list: inout [Int]) {
120+
121+
var sublistCount = list.count / 2
122+
123+
while sublistCount > 0 {
126124
127-
swap(&arr[index], &arr[index + n])
125+
for index in 0..<list.count {
126+
127+
guard index + sublistCount < list.count else { break }
128+
129+
if list[index] > list[index + sublistCount] {
130+
swap(&list[index], &list[index + sublistCount])
131+
}
132+
133+
guard sublistCount == 1 && index > 0 else { continue }
134+
135+
if list[index - 1] > list[index] {
136+
swap(&list[index - 1], &list[index])
137+
}
128138
}
139+
sublistCount = sublistCount / 2
129140
}
130-
131-
n = n / 2
132-
133-
}while n > 0
141+
}
142+
143+
shellSort(&arr)
134144
```
135145

136146
## See also

0 commit comments

Comments
 (0)