我正在尝试计算合并排序中的掉期。这似乎是一个非常直截了当的命题,但似乎我的逻辑存在问题。
这是我的代码的相关部分,我正在尝试增加计数:
while leftIndex < leftPile.count && rightIndex < rightPile.count {
if leftPile[leftIndex] < rightPile[rightIndex] {
// nothing swapped here
orderedPile.append(leftPile[leftIndex])
leftIndex += 1
} else if leftPile[leftIndex] > rightPile[rightIndex] {
orderedPile.append(rightPile[rightIndex])
// item taken from right pile == swapped -> increment swapCount
swapCount += 1
rightIndex += 1
} else {
orderedPile.append(leftPile[leftIndex])
leftIndex += 1
// item taken from left pile == swapped -> increment swapCount
swapCount += 1
orderedPile.append(rightPile[rightIndex])
rightIndex += 1
}
}
出于某种原因,我使用以下数组计算5次掉期:
unsortedArray = [2, 1, 3, 1, 2]
sortedArray = [1, 1, 2, 2, 3]
swapCount = 5
这是我的全班:
class MergeSortWithCounter {
var swapCount: Int64
init() {
swapCount = 0
}
func mergeSort<T: Comparable>(_ array: [T]) -> [T] {
guard array.count > 1 else { return array }
let middleIndex = array.count / 2
let leftArray = mergeSort(Array(array[0..<middleIndex]))
let rightArray = mergeSort(Array(array[middleIndex..<array.count]))
return merge(leftPile: leftArray, rightPile: rightArray)
}
func merge<T: Comparable>(leftPile: [T], rightPile: [T]) -> [T] {
var leftIndex = 0
var rightIndex = 0
var orderedPile = [T]()
if orderedPile.capacity < leftPile.count + rightPile.count {
orderedPile.reserveCapacity(leftPile.count + rightPile.count)
}
while leftIndex < leftPile.count && rightIndex < rightPile.count {
if leftPile[leftIndex] < rightPile[rightIndex] {
// nothing swapped here
orderedPile.append(leftPile[leftIndex])
leftIndex += 1
} else if leftPile[leftIndex] > rightPile[rightIndex] {
orderedPile.append(rightPile[rightIndex])
// item taken from right pile == swapped -> increment swapCount
swapCount += 1
rightIndex += 1
} else {
orderedPile.append(leftPile[leftIndex])
leftIndex += 1
// item taken from left pile == swapped -> increment swapCount
swapCount += 1
orderedPile.append(rightPile[rightIndex])
rightIndex += 1
}
}
while leftIndex < leftPile.count {
orderedPile.append(leftPile[leftIndex])
leftIndex += 1
}
while rightIndex < rightPile.count {
orderedPile.append(rightPile[rightIndex])
rightIndex += 1
}
return orderedPile
}
}
我知道我错过了一些超级简单的东西,但是我花了更多的时间来承认弄清楚我的错误在哪里。
感谢您阅读!
答案 0 :(得分:1)
当你不必这样做时,你会在相同的情况下进行交换:
if leftPile[leftIndex] < rightPile[rightIndex] {
// nothing swapped here
你的意思是
if leftPile[leftIndex] <= rightPile[rightIndex] {
// nothing swapped here