Thursday, February 15, 2018

Implementing Bubble Sort in Golang

What Is Bubble Sort ?
Bubble sort is a simple sorting algorithm that sequentially goes through an array n times. Each time the algorithm runs through the array, it looks at the first element and then the second element, if the first element is larger than the second element then it swaps them, it then proceeds through the entire list performing this action.


Time Complexity
The time complexity for this algorithm is O(n^2) where n is the number of items being sorted. It is not recommended to use for large input sets.
Best case time complexity is O(n) when the list is already sorted.



Implementation

package main

import (
    "fmt"
)

var arrToBeSorted [10]int = [10]int{1,3,2,5,4,6,7,9,8,10}

func BubbleSort(input [10]int) {
    for i := 0; i < len(input)-1; i++ {
        if input[i] > input[i+1] {
            input[i], input[i+1] = input[i+1], input[i]
        }
    }
    fmt.Println(input)
}


func main() {
    fmt.Println("Before")
    fmt.Println(arrToBeSorted)
  
    fmt.Println("After")
    BubbleSort(arrToBeSorted)
  
}


 Result:








Other Topics:





No comments:

Post a Comment