Skip to content

Instantly share code, notes, and snippets.

@valchonedelchev
Created July 18, 2020 12:43
Show Gist options
  • Save valchonedelchev/69a87b88853770e27ada6a229e453b8d to your computer and use it in GitHub Desktop.
Save valchonedelchev/69a87b88853770e27ada6a229e453b8d to your computer and use it in GitHub Desktop.
Bubble sort implementation in Go using optimised algorithm from https://en.wikipedia.org/wiki/Bubble_sort
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
fmt.Print("Please enter integer sequence space separated and hit enter: ")
integers := ReadInput()
BubbleSort(integers)
fmt.Println(integers)
}
// ReadInput will read use input from stdin
func ReadInput() []int {
var is []int
scanner := bufio.NewScanner(os.Stdin)
if scanner.Scan() {
input := scanner.Text()
integers := strings.Fields(input)
for _, i := range integers {
if iv, err := strconv.Atoi(i); err == nil {
is = append(is, iv)
}
}
}
return is
}
// BubbleSort function for 2 points
func BubbleSort(s []int) {
n := len(s)
for {
newn := 0
for i := 1; i <= n-1; i++ {
if s[i-1] > s[i] {
Swap(s, i-1)
newn = i
}
}
n = newn
if n <= 1 {
break
}
}
}
// Swap function for 2 points
func Swap(s []int, i int) {
s[i+1], s[i] = s[i], s[i+1]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment