From ad9fdae5ae65ae238325bedee6fef90c1368bf6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=B5=E7=91=9C=E7=91=9C?= Date: Sat, 4 Feb 2023 17:57:30 +0800 Subject: [PATCH] Bugfix for failing to sort correctly Fix issue as below: https://github.com/kodecocodes/swift-algorithm-club/issues/1011 --- .../Sources/Comb Sort.swift | 23 ++++++++----------- Comb Sort/Comb Sort.swift | 23 ++++++++----------- 2 files changed, 20 insertions(+), 26 deletions(-) diff --git a/Comb Sort/Comb Sort.playground/Sources/Comb Sort.swift b/Comb Sort/Comb Sort.playground/Sources/Comb Sort.swift index 559fe47e8..72db871db 100644 --- a/Comb Sort/Comb Sort.playground/Sources/Comb Sort.swift +++ b/Comb Sort/Comb Sort.playground/Sources/Comb Sort.swift @@ -7,25 +7,22 @@ import Foundation -public func combSort(_ input: [T]) -> [T] { - var copy: [T] = input +public func combSort(_ input: [T]) -> [T] { + var copy = input var gap = copy.count - let shrink = 1.3 + var done = false - while gap > 1 { - gap = (Int)(Double(gap) / shrink) - if gap < 1 { - gap = 1 - } - - var index = 0 - while !(index + gap >= copy.count) { + while gap > 1 || !done { + gap = max(gap * 10 / 13, 1) + done = true + for index in 0 ..< copy.count - gap { if copy[index] > copy[index + gap] { - copy.swapAt(index, index + gap) + copy.swapAt(index, index + gap) + done = false } - index += 1 } } + return copy } diff --git a/Comb Sort/Comb Sort.swift b/Comb Sort/Comb Sort.swift index bd37fed42..72db871db 100644 --- a/Comb Sort/Comb Sort.swift +++ b/Comb Sort/Comb Sort.swift @@ -7,25 +7,22 @@ import Foundation -public func combSort(_ input: [T]) -> [T] { - var copy: [T] = input +public func combSort(_ input: [T]) -> [T] { + var copy = input var gap = copy.count - let shrink = 1.3 - - while gap > 1 { - gap = (Int)(Double(gap) / shrink) - if gap < 1 { - gap = 1 - } - - var index = 0 - while !(index + gap >= copy.count) { + var done = false + + while gap > 1 || !done { + gap = max(gap * 10 / 13, 1) + done = true + for index in 0 ..< copy.count - gap { if copy[index] > copy[index + gap] { copy.swapAt(index, index + gap) + done = false } - index += 1 } } + return copy }