Dutch Flag problem

Below is my attempt to the dutch flag problem. My algorithms isn't showing the right output. How do I fix this ?
Expected output:
a = [5,2,4,4,6,4,4,3] and pivot = 4 --> result = [3,2,4,4,4,4,5,6].
My Output:
[3, 2, 4, 4, 4, 4, 4, 3]

func swapElements (_ array: inout [Int], _ a:inout Int, _ b: inout Int)->Int{
    var temp = array[a]
    array[a] = array[b]
    temp =  array[b]

    return temp
}


func dutchNationalFlag(flags: inout [Int])->[Int]{
    var lowerBound = 0
    var highBound = flags.count-1
    var i = 0
    while i <= highBound{
        if flags[i] < 4{
            swapElements(&flags, &i, &lowerBound)
            lowerBound+=1
            i+=1
        }

        else if flags[i] > 4{
            swapElements(&flags, &i, &highBound)
            highBound -= 1
        }

        else {
            i+=1
        }
    }
    return flags

}
var nums = [5,2,4,4,6,4,4,3]
dutchNationalFlag(flags: &nums)

Figuring out why some code doesn't work is a key skill to develop as you learn to code!

One of the most important advantages to splitting up your code into functions is that you can then test each function separately to make sure that each one is doing a much less complicated thing correctly.

Notice that you have two functions. The first one is named swapElements.

  • What do you expect that function to do? Can you explain its behavior in words?
  • When you translate those words into Swift code, does it match what you've written?
  • For example input arguments of your choosing, what output do you expect from swapElements, and does your function actually meet those expectations?

That should be enough to get you started on debugging your code.

4 Likes