Home > Mobile >  How to implement a Bubble Sort in an Unordered list in Go
How to implement a Bubble Sort in an Unordered list in Go

Time:10-07

In the below code I have implemented a bubble sort algorithm using golang. But I am unable to figure out what I am doing wrong in the code. Please help me out with this.

func main() {

    slice := generateSlice(20)
    fmt.Println("\n--- Unsorted --- \n\n", slice)
    bubblesort(slice)
    fmt.Println("\n--- Sorted ---\n\n", slice, "\n")
}

// Generates a slice of size, size filled with random numbers
func generateSlice(size int) []int {

    slice := make([]int, size, size)
    rand.Seed(time.Now().UnixNano())
    for i := 0; i < size; i   {
        slice[i] = rand.Intn(999) - rand.Intn(999)
    }
    return slice
}

func bubblesort(items []int) {
    var (
        n      = len(items)
        sorted = false
    )
    for sorted {
        swapped := false
        for i := 0; i < n-1; i   {
            if items[i] > items[i 1] {
                items[i 1], items[i] = items[i], items[i 1]
                swapped = true
            }
        }
        if !swapped {
            sorted = true
        }
        n = n - 1
    }
}

CodePudding user response:

There is a minor error in the code which is the problem for not returning the correct value of the sorted slice.

use !sorted in place of sorted in the iteration of the bubble sort function.

The code will be -

func main() {

    slice := generateSlice(20)
    fmt.Println("\n--- Unsorted --- \n\n", slice)
    bubblesort(slice)
    fmt.Println("\n--- Sorted ---\n\n", slice, "\n")
}

func generateSlice(size int) []int {

    slice := make([]int, size, size)
    rand.Seed(time.Now().UnixNano())
    for i := 0; i < size; i   {
        slice[i] = rand.Intn(999) - rand.Intn(999)
    }
    return slice
}

func bubblesort(items []int) {
    var (
        n      = len(items)
        sorted = false
    )
    for !sorted {
        swapped := false
        for i := 0; i < n-1; i   {
            if items[i] > items[i 1] {
                items[i 1], items[i] = items[i], items[i 1]
                swapped = true
            }
        }
        if !swapped {
            sorted = true
        }
        n = n - 1
    }
}
  •  Tags:  
  • go
  • Related