For循环vs While循环-荷兰国旗

时间:2020-10-05 16:24:55

标签: algorithm loops for-loop go while-loop

我正在尝试在golang中使用for循环和while循环来实现荷兰国旗问题。

问题陈述- 对于给定的阵列,以这样的方式布置元素:大于枢轴的元素在枢轴的右侧,小于阵列的元素在阵列的左侧。 示例-

输入-[3 2 4 1 6 3 7 5],枢轴= 4

输出-[3 2 1 3 4 7 5 6]

用于循环实现[不能按预期工作]

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)

}

在循环实现中[按预期工作]-

    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循环实现中发现问题。

1 个答案:

答案 0 :(得分:1)

问题在于,如果您同时更新while循环计数器i,仅适用于两个条件,即

    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)

}