algorithm - For 循环 vs While 循环 - 荷兰国旗
问题描述
我正在尝试在golang中使用for循环和while循环来实现荷兰国旗问题。
问题陈述 - 对于给定的数组,以这样一种方式排列元素,即大于枢轴的元素位于枢轴的右侧,小于数组的元素位于数组的左侧。例子 -
输入 - [3 2 4 1 6 3 7 5] ,枢轴 = 4
输出 - [3 2 1 3 4 7 5 6]
For循环实现[不按预期工作]
package main
import (
"fmt"
)
func main() {
in := []int{3, 2, 4, 1, 6, 3, 7, 5}
pivot := 4
run(in, pivot)
}
func run(in []int, pivot int) {
fmt.Println("before : ", in)
lBoundary := 0
hBoundary := len(in) - 1
for i := 0; i <= hBoundary; i++ {
if in[i] > pivot {
in[i], in[hBoundary] = in[hBoundary], in[i]
hBoundary--
} else if in[i] < pivot {
in[i], in[lBoundary] = in[lBoundary], in[i]
lBoundary++
}
}
fmt.Println("after: ", in)
}
While 循环实现 [按预期工作] -
package main
import (
"fmt"
)
func main() {
in := []int{3, 2, 4, 1, 6, 3, 7, 5}
pivot := 4
run(in, pivot)
}
func run(in []int, pivot int) {
fmt.Println("before : ", in)
i := 0
lBoundary := 0
hBoundary := len(in) - 1
for i <= hBoundary {
if in[i] > pivot {
in[i], in[hBoundary] = in[hBoundary], in[i]
hBoundary--
} else if in[i] < pivot {
in[i], in[lBoundary] = in[lBoundary], in[i]
lBoundary++
i++
} else {
i++
}
}
fmt.Println("after: ", in)
}
我无法确定 for 循环实现中的问题。
解决方案
i
问题是,如果您仅针对两个条件更新 while 循环计数器,即
else if in[i] < pivot {
in[i], in[lBoundary] = in[lBoundary], in[i]
lBoundary++
i++
} else {
i++
}
但是在 for 循环的情况下,每次执行循环时计数器都会增加,因为i++
.
因此,如果您更新 for 循环代码以将增量条件放在循环内,它将按预期运行:
package main
import (
"fmt"
)
func main() {
in := []int{3, 2, 4, 1, 6, 3, 7, 5}
pivot := 4
run(in, pivot)
}
func run(in []int, pivot int) {
fmt.Println("before : ", in)
lBoundary := 0
hBoundary := len(in) - 1
// remove i++ condition
for i := 0; i <= hBoundary; {
if in[i] > pivot {
in[i], in[hBoundary] = in[hBoundary], in[i]
hBoundary-- // no increment in this condition
} else if in[i] < pivot {
in[i], in[lBoundary] = in[lBoundary], in[i]
lBoundary++
i++ // add the increment condition here
} else {
i++ // and here as well
}
}
fmt.Println("after: ", in)
}
推荐阅读
- if-statement - 打开 Refine IF 语句
- tabulator - ajaxProgressiveLoad="load"、initialFilter 和 ajaxURLGenerator
- ruby-on-rails - 如果验证为假,如何停止迁移?
- flask - 烧瓶,SQLAlchemy,数据表 - ImportError:无法在 Models.py 中导入名称“db”
- python - PEP 8:如何为名为 a2b 的库命名首字母缩写词?
- docker - Docker Stack/Compose Redis 实例不持久化数据
- python - 在python中使用lambda函数存储字典
- swift - UISwipeGesture 未注册第一次滑动
- python - 将从csv读取的多列数据排序到Python3列表中不起作用
- excel - 使用 Excel 宏重新格式化单元格内容