我正在尝试创建两个用于对数组进行排序的函数-第一个用于冒泡排序,第二个用于插入排序。它们两者都不仅应返回排序后的数组,而且还应返回排序过程中发生的比较和交换次数。我该怎么办?
这是我当前的代码:
func insertionSort(a: [Int]) -> (comparisonsCount: Int, swapsCount: Int, sortedArray: [Int]) {
guard a.count > 1 else { return (0, 0, a) }
var comparisons = 0
var swaps = 0
var b = a
for i in 1..<b.count {
var y = i
while y > 0 && b[y] < b[y - 1] {
b.swapAt(y - 1, y)
y -= 1
}
}
return (comparisons, swaps, b)
}
func bubbleSort(a: [Int]) -> (comparisonsCount: Int, swapsCount: Int, sortedArray: [Int]) {
var b = a
var comparisons = 0
var swaps = 0
for i in 0..<a.count-1 {
for j in 0..<a.count-i-1 {
if(b[j] > b[j+1]) {
let temp = b[j]
b[j] = b[j+1]
b[j+1] = temp
swaps += 1
}
comparisons += 1
}
}
return (comparisons, swaps, b)
}
答案 0 :(得分:0)
func insertionSort(a: [Int]) -> (comparisonsCount: Int, swapsCount: Int, sortedArray: [Int]) {
guard a.count > 1 else { return (0, 0, a) }
var comparisons = 0
var swaps = 0
var b = a
for i in 1..<b.count {
var y = i
comaprisons += 2 // two comparison in while and it will happen at least once
while y > 0 && b[y] < b[y - 1] {
b.swapAt(y - 1, y)
y -= 1
swaps += 1
comparisons += 2
}
if (y == 0){
comparisons -= 1 // && Operator short circuiting explanation below
}
}
return (comparisons, swaps, b)
}
&&和||操作员都是短路操作员。因此,如果在内部while循环中输入y-= 1会导致y == 0。在这种情况下,b [y]