Skip to content

Instantly share code, notes, and snippets.

@raninho
Created December 4, 2018 22:20
Show Gist options
  • Save raninho/36056dddae6f603dd4278acef133a4f7 to your computer and use it in GitHub Desktop.
Save raninho/36056dddae6f603dd4278acef133a4f7 to your computer and use it in GitHub Desktop.
BubbleSort example
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
type name struct {
fname string
lname string
}
func Swap(values []int, pos int) {
temp := values[pos]
values[pos] = values[pos+1]
values[pos+1] = temp
}
func BubbleSort(values []int) {
for n := len(values); n > 1; n-- {
for i := 0; i < n-1; i++ {
if values[i] > values[i+1] {
Swap(values, i)
}
}
}
}
func main() {
values := make([]int, 0, 10)
scanner := bufio.NewScanner(os.Stdin)
//scanner.Split(bufio.ScanWords)
fmt.Printf("Please enter integer numbers: ")
scanner.Scan()
valstring := scanner.Text()
for _, sval := range strings.Split(valstring, " ") {
val, err := strconv.Atoi(sval)
if err == nil {
values = append(values, val)
} else {
fmt.Printf("Error parsing the integer %s\n", sval)
}
}
BubbleSort(values)
fmt.Printf("sorted: %v\n", values)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment