DEV Community

Discussion on: Sorting Algorithms in Go

Collapse
 
jacobalberty profile image
Jacob Alberty

Your bubble sort contains an error. The output is [1 2 9 7 39 11 54] which is clearly not fully sorted. It only does one iteration. Just need to add an isDone = false inside of the if statement

package main

import "fmt"

func main() {
    var n = []int{1, 39, 2, 9, 7, 54, 11}

    var isDone = false

    for !isDone {
        isDone = true
        var i = 0
        for i < len(n)-1 {
            if n[i] > n[i+1] {
                n[i], n[i+1] = n[i+1], n[i]
                isDone = false
            }
            i++
        }
    }

    fmt.Println(n)
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
adnanbabakan profile image
Adnan Babakan (he/him)

Thank you so much for spotting the error. Don't know how missed that. :)