Skip to content

Commit ad9fdae

Browse files
committed
Bugfix for failing to sort correctly
Fix issue as below: kodecocodes#1011
1 parent e592ed6 commit ad9fdae

File tree

2 files changed

+20
-26
lines changed

2 files changed

+20
-26
lines changed

Comb Sort/Comb Sort.playground/Sources/Comb Sort.swift

+10-13
Original file line numberDiff line numberDiff line change
@@ -7,25 +7,22 @@
77

88
import Foundation
99

10-
public func combSort<T: Comparable>(_ input: [T]) -> [T] {
11-
var copy: [T] = input
10+
public func combSort<T: Comparable>(_ input: [T]) -> [T] {
11+
var copy = input
1212
var gap = copy.count
13-
let shrink = 1.3
13+
var done = false
1414

15-
while gap > 1 {
16-
gap = (Int)(Double(gap) / shrink)
17-
if gap < 1 {
18-
gap = 1
19-
}
20-
21-
var index = 0
22-
while !(index + gap >= copy.count) {
15+
while gap > 1 || !done {
16+
gap = max(gap * 10 / 13, 1)
17+
done = true
18+
for index in 0 ..< copy.count - gap {
2319
if copy[index] > copy[index + gap] {
24-
copy.swapAt(index, index + gap)
20+
copy.swapAt(index, index + gap)
21+
done = false
2522
}
26-
index += 1
2723
}
2824
}
25+
2926
return copy
3027
}
3128

Comb Sort/Comb Sort.swift

+10-13
Original file line numberDiff line numberDiff line change
@@ -7,25 +7,22 @@
77

88
import Foundation
99

10-
public func combSort<T: Comparable>(_ input: [T]) -> [T] {
11-
var copy: [T] = input
10+
public func combSort<T: Comparable>(_ input: [T]) -> [T] {
11+
var copy = input
1212
var gap = copy.count
13-
let shrink = 1.3
14-
15-
while gap > 1 {
16-
gap = (Int)(Double(gap) / shrink)
17-
if gap < 1 {
18-
gap = 1
19-
}
20-
21-
var index = 0
22-
while !(index + gap >= copy.count) {
13+
var done = false
14+
15+
while gap > 1 || !done {
16+
gap = max(gap * 10 / 13, 1)
17+
done = true
18+
for index in 0 ..< copy.count - gap {
2319
if copy[index] > copy[index + gap] {
2420
copy.swapAt(index, index + gap)
21+
done = false
2522
}
26-
index += 1
2723
}
2824
}
25+
2926
return copy
3027
}
3128

0 commit comments

Comments
 (0)